【问题标题】:How to filter parents based on multiple children django如何根据多个孩子django过滤父母
【发布时间】:2018-09-22 00:04:41
【问题描述】:

我在这里找到了一个相关的问题: How can filter parent based on children in django

但是,我一直在努力寻找有特定孩子的父母。

使用与相关问题相同的模型:

class Kid(models.Model):
    name = models.CharField(max_length=200)

class Toy(models.Model):
    name = models.CharField(max_length=200)
    material = models.CharField(max_length=200)
    owner = models.ForeignKey(Kid)

如何找到拥有特定玩具的孩子?

Kid.objects.distinct().filter( ( toy__name='x' and toy__material='plastic')
                   and another ( toy__name='y' and toy__material='wood' )
                   and another ( toy__name='z' and toy__material='metal' )
                   and another .... )

【问题讨论】:

    标签: django


    【解决方案1】:

    我找到了解决问题的方法,真不敢相信我错过了这个......

    继续为每个玩具需求的 Kid 查询添加过滤器,如下所示:

    Kid.objects.filter(toy__name='x', toy__material='plastic').\
       filter( toy__name='y', toy__material='wood' ).\
       filter( toy__name='z', toy__material='metal' )
    

    【讨论】:

    • 您可以将自己对问题的答案标记为答案。我已经多次返回这个答案,这是一个非常好的解决方案!
    猜你喜欢
    • 2017-02-07
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    相关资源
    最近更新 更多