我在这里找到了一个相关的问题: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 .... )
我找到了解决问题的方法,不敢相信我错过了这个......
只需继续为每个玩具需求的 Kid 查询添加过滤器,如下所示:
Kid.objects.filter(toy__name='x', toy__material='plastic').\
filter( toy__name='y', toy__material='wood' ).\
filter( toy__name='z', toy__material='metal' )
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句