1

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>]
Mathieu Marques
  • 1,678
  • 15
  • 33

2 Answers2

1

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.

nik_m
  • 11,825
  • 4
  • 43
  • 57
0

In case you want to log an exception, if the corresponding query is not successful:

try: parent = Parent.objects.get(item=20, item__kind=10) except Exception as e: print "[CRITICAL] <some_view.py> - {}".format(e)

Abijith Mg
  • 2,647
  • 21
  • 35