我可以在不诉诸两个查询的情况下完成以下工作吗?
>>> 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
我可以在不诉诸两个查询的情况下完成以下工作吗?
>>> 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
Q 对象提供了您正在寻找的功能。https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
使用Q
对象。
from django.db.models import Q
len(Document.objects.filter( Q(category=c) | Q(category=None) ) )