Python – Django: Filter by values in None, Other

Django: Filter by values in None, Other… here is a solution to the problem.

Django: Filter by values in None, Other

I’m having the same issue as OP in this thread: Django – filtering by “certain value or None” :

I have a field in an data object that can be either null or set to
some integer. I want, given an integer, to filter all the objects with
that integer value OR none:

MyElements.objects.all().filter(value__in=[myInt, None]) # Query 1

However, this line does not work for elements with null value. More
precisely:

MyElements.objects.all().filter(value__in=[None]) # Query 2

returns nothing. whereas

MyElements.objects.all().filter(value = None) # Query 3

returns the null-valued elements.

How can I rewrite the original query (which involves myInt) correctly?

I

know the OP has accepted an answer, but I’m wondering why query 2 didn’t produce any results.

Solution

It is executed according to SQL rules. NULL values are not the actual values to be compared. This is an unknown value.

Read more about this here: is null vs == null

In Django, you can get records with NULL values like this:

MyElements.objects.filter(value__isnull = True)

So you need to filter out None in the comparison list first, and then add it to your query by yourself.

from django.db.models import Q
MyElements.objects.filter(Q(value__in = [list_of_vals]) | Q(value__isnull = True))

Related Problems and Solutions