0

我可以在不诉诸两个查询的情况下完成以下工作吗?

>>> c = Category.objects.all()[0]
>>> len(Document.objects.filter(category=c))
3
>>> len(Document.objects.filter(category=None))
55
>>> len(Document.objects.filter(category__in=[c, None]))
3
4

2 回答 2

2

Q 对象提供了您正在寻找的功能。https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

于 2012-04-17T18:32:05.053 回答
2

使用Q对象

from django.db.models import Q
len(Document.objects.filter( Q(category=c) | Q(category=None) ) )
于 2012-04-17T18:32:17.760 回答