【问题标题】:Django lookup multiple models reusing querysetsDjango 使用查询集查找多个模型
【发布时间】:2017-12-12 19:12:11
【问题描述】:

假设我想获取所有者的汽车座椅为红色的房屋列表。

我可以这样做:

queryset.filter(owner__cars__seats__color='red')

但是,我想重用获取有红色座椅的汽车的过滤器,所以我有一个关于汽车的自定义查询集。

class CarsQuerySet(models.QuerySet):
    def with_red_seats(self):
         return self.filter(seats__color='red')

有没有办法在第一个查询中重用“with_red_seats”过滤器?

类似这样的东西,显然行不通:

queryset.filter(owner__cars__with_red_seats)

【问题讨论】:

    标签: django


    【解决方案1】:

    如果您想重复使用:

    red_seated_cars = Cars.objects.with_red_seats()
    House.objects.filter(owner__cars__in = red_seated_cars)
    

    可能会成功

    【讨论】:

    • 我更希望有一个更优雅的解决方案,但这可行。
    猜你喜欢
    • 1970-01-01
    • 2012-12-15
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 2018-02-09
    • 2018-12-04
    • 1970-01-01
    相关资源
    最近更新 更多