【问题标题】:Filtering via manually defined ManyToMany through models in Django通过Django中的模型通过手动定义的ManyToMany进行过滤
【发布时间】: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 暗示 - 尽可能高效地获取 HouseImageorder 属性中具有最低值的所有 House 对象。
  • 如果你使用的是postgresql,试试HouseImage.objects.distinct('house').order_by('-order')[0]

标签: django django-models


【解决方案1】:

您可以预取相关的没有额外的查询。例如:

houses = House.objects.prefetch_related('houseimage_set__image')

然后,当您循环房屋或正在做的任何事情时,您可以获得最低顺序的图像,如下所示:

for house in houses:
    houseimages = house.houseimage_set.order_by('order')
    if houseimages:
        image = houseimages[0].image
    else:
        image = None
    …

编辑:在深入研究之后,每次调用.order_by 时,django 似乎都会进行另一个查询。因此,在这种情况下,您可能必须手动订购houseimages。例如:

houseimages = sorted(house.houseimage_set.all(), key=lambda x: x.order) 

【讨论】:

    猜你喜欢
    • 2012-06-12
    • 2021-06-07
    • 2022-11-18
    • 2016-07-23
    • 2019-12-04
    • 1970-01-01
    • 2016-08-05
    • 2015-07-09
    • 2016-06-16
    相关资源
    最近更新 更多