我在这里找到了一个相关的问题: 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 .... )
答案 0 :(得分:0)
我找到了解决问题的办法,无法相信我错过了这个......
只需继续为Kid查询添加过滤器,以满足每个玩具需求:
Kid.objects.filter(toy__name='x', toy__material='plastic').\
filter( toy__name='y', toy__material='wood' ).\
filter( toy__name='z', toy__material='metal' )