Search code examples
djangodjango-modelsmany-to-manydjango-querysetdjango-orm

How to filter on 2 attributes at once with Django ORM


I have the following models:

class Parent(models.Model):
    item_involved = models.ManyToManyField(Item, through=ItemInvolved)


class ItemInvolved(models.Model):
    parent = models.ForeignKey(Parent, related_name='item_involvement')
    item = models.ForeignKey(Item)
    kind = models.PositiveIntegerField()

I want to retrieve all Parents for which an Item has pk=20 and its ItemInvolved has kind=10.

Edit:

Say I have the following objects:

Parent(pk=1)
Parent(pk=2)
Parent(pk=3)
ItemInvolved(pk=11, parent=1, item=18, kind=10)
ItemInvolved(pk=12, parent=1, item=19, kind=10)
ItemInvolved(pk=13, parent=1, item=20, kind=10)
ItemInvolved(pk=14, parent=2, item=20, kind=10)
ItemInvolved(pk=15, parent=3, item=19, kind=10)
ItemInvolved(pk=16, parent=3, item=20, kind=20)

I need a query that will yield:

[<Parent: 1>, <Parent: 2>]

Solution

  • parents = Parent.objects.filter(item=20, item__kind=10)

    OK. Got it.

    parents = Parent.objects.filter(item_involved=20, item_involvement__kind=10)
    

    Further explanation on spanning multi valued relationship.