【问题标题】:Django: filter ForeignKey in value or NoneDjango:在值或无中过滤 ForeignKey
【发布时间】:2026-02-15 03:30:01
【问题描述】:

我可以在不诉诸两个查询的情况下使以下内容工作吗?

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

【问题讨论】:

  • 预期结果如何?
  • 如果您想要所有类别的计数,Document.objects.values('category').annotate(count=Count('category')).order_by()
  • 实际上并不想要计数。这只是为了说明目的。

标签: python django django-queryset


【解决方案1】:

使用Q object

from django.db.models import Q
len(Document.objects.filter( Q(category=c) | Q(category=None) ) )

【讨论】:

  • @agf 实际上,如果您打算评估查询集,这实际上是无效的。
【解决方案2】: