Django Query __isnull=True or = None

DjangoDjango ModelsDjango Queryset

Django Problem Overview


this is a simple question. I'd like to know if it is the same to write:

queryset = Model.objects.filter(field=None)

than:

queryset = Model.objects.filter(field__isnull=True)

I'm using django 1.8

Django Solutions


Solution 1 - Django

They are equal:

>>> str(Person.objects.filter(age__isnull=True).query) == str(Person.objects.filter(age=None).query)
True
>>> print(Person.objects.filter(age=None).query)
SELECT "person_person"."id", "person_person"."name", "person_person"."yes", "person_person"."age" FROM "person_person" WHERE "person_person"."age" IS NULL
>>> print(Person.objects.filter(age__isnull=True).query)
SELECT "person_person"."id", "person_person"."name", "person_person"."yes", "person_person"."age" FROM "person_person" WHERE "person_person"."age" IS NULL

Exclusion: the Postgres JSON field (see the answer of @cameron-lee)

Solution 2 - Django

It depends on the type of field. As mentioned in other answers, they are usually equivalent but in general, this isn't guaranteed.

For example, the Postgres JSON field uses =None to specify that the json has the value null while __isnull=True means there is no json:

https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield

null json vs no json

Solution 3 - Django

Just to keep in mind that you cannot reverse the condition with your first solution:

# YOU CANNOT DO THIS
queryset = Model.objects.filter(field!=None)

However you can do this:

queryset = Model.objects.filter(field__isnull=False)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlejandro VeintimillaView Question on Stackoverflow
Solution 1 - DjangoknbkView Answer on Stackoverflow
Solution 2 - DjangoCameron LeeView Answer on Stackoverflow
Solution 3 - DjangoManan MehtaView Answer on Stackoverflow