【发布时间】:2013-09-18 14:54:42
【问题描述】:
我的 models.py 看起来像这样:
class House(models.Model):
images = models.ManyToManyField('Image', through='HouseImage')
class HouseImage(models.Model):
house = models.ForeignKey('House')
image = models.ForeignKey('Image')
order = models.IntegerField(default=99)
class Image(models.Model):
url = models.CharField(max_length=200)
我无法编写代码来获取所有 House 对象,并为每个房子提供一个 order 属性值最低的图像。有没有办法做到这一点,并且不会像 House 对象那样多次访问数据库?
编辑:
HouseImage 表
house image order
1 1 1
1 2 2
1 3 3
2 4 2
2 5 1
3 6 1
图像表
id url
1 a
2 b
3 c
4 d
5 e
6 f
我的 django 查询集中需要以下结果:
house_id image_url
1 a
2 e
3 f
我希望现在更清楚了。
【问题讨论】:
-
你的问题还不清楚。
-
@GamesBrainiac - OP 暗示 - 尽可能高效地获取
HouseImage中order属性中具有最低值的所有 House 对象。 -
如果你使用的是postgresql,试试
HouseImage.objects.distinct('house').order_by('-order')[0]
标签: django django-models