如何使用 Django ORM 一次过滤 2 个属性

How to filter on 2 attributes at once with Django ORM

我有以下型号:

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

我想检索所有 ParentItem 有 pk=20 并且它的 ItemInvolved 有 kind=10.

编辑:

假设我有以下对象:

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)

我需要一个将产生的查询:

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

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

好的。知道了。

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

关于spanning multi valued relationship的进一步解释。

万一要记录异常,如果对应的查询不成功:

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