bwrabbit
bwrabbit

Reputation: 529

How to filter parents based on multiple children django

I found a related question here: How can filter parent based on children in django

However, I am stuck trying to find the parents who have a specific set of children.

Using the same models as the related question:

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)

How can I find Kids who have a specific set of toys?

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 .... )

Upvotes: 1

Views: 1199

Answers (1)

bwrabbit
bwrabbit

Reputation: 529

I found a solution to my problem, can't believe I missed this...

Just keep adding filters to the Kid query for each toy requirement like so:

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

Upvotes: 1

Related Questions