2 つのクエリに頼らずに以下を機能させることはできますか?
>>> 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
2 つのクエリに頼らずに以下を機能させることはできますか?
>>> 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) ) )