Django filter which may include None

Viewed 1921

Is there a way to include None when filtering on a list of values?

>>> MyModel.objects.filter(amount=10).count()
9
>>> MyModel.objects.filter(amount=None).count()
30
>>> MyModel.objects.filter(amount__in=[10]).count()
9
>>> MyModel.objects.filter(amount__in=[None, 10]).count()
9

I would expect the last call to return 39, rather than 9.

In my actual use case None may or may not be included in the list of values to be filtered on. I could use an if/else block to check for None in the list of values and construct the query using Q objects if needed, but doing so for a large number of filters is going to be a mess. There must be a better way, right?

1 Answers
Related