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

时间:2017-03-08 11:58:30

标签: django django-models many-to-many django-queryset 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()

我想检索Parent pk = 20且Item种类= 10的所有ItemInvolved

编辑:

说我有以下物品:

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>]

2 个答案:

答案 0 :(得分:1)

<德尔> parents = Parent.objects.filter(item=20, item__kind=10)

行。明白了。

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

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

答案 1 :(得分:0)

如果您想记录异常,如果相应的查询不成功:

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