Jesse Aldridge
Jesse Aldridge

Reputation: 8149

Django: filter ForeignKey in value or None

Can I get the following to work without resorting to two queries?

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

Upvotes: 1

Views: 1471

Answers (2)

freakish
freakish

Reputation: 56477

Use Q object.

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

Upvotes: 2

dm03514
dm03514

Reputation: 55962

Q objects provide the functionality you are loking for. https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

Upvotes: 2

Related Questions