Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Query __isnull=True or = None

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

like image 284
Alejandro Veintimilla Avatar asked Apr 24 '15 22:04

Alejandro Veintimilla


People also ask

Is __ null Django?

In Django queryset we have __isnull to check if a value is null. Here were filtering all the values from MyModel model, which have an alias = Null. exclude allows you to pass multiple arguments, it will the then check for every argument. If your query is still more complex, you can use Django's Q Objects.

What is Select_related in Django?

Using select_related() Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects.


1 Answers

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)

like image 94
knbk Avatar answered Sep 22 '22 22:09

knbk