[Django]-Django case when else in filter

5👍

You should not wrap this in a Q object, since a Q object is a condition, a Case is not something that can be True or False:

from django.db.models import Case, When

model.objects.filter(a=Case(When(x__isnull=True, then='b'), default='c'))

Note that you can replace x__isnull=True with simply x=None, which is slightly shorter:

from django.db.models import Case, When

model.objects.filter(a=Case(When(x=None, then='b'), default='c'))

Leave a comment