Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: filtering queryset by 'field__isnull=True' or 'field=None'?

I have to filter a queryset by a dynamic value (which can be None): may I simply write:

filtered_queryset = queryset.filter(field=value) 

or shall I check for None:

if value is None:     filtered_queryset = queryset.filter(field__isnull=True) else:     filtered_queryset = queryset.filter(field=value) 

Does the behaviour depend on the particular DBMS?

like image 475
Don Avatar asked May 03 '13 09:05

Don


People also ask

Is null Django Queryset?

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.

How check field is null in Django?

Unless you set null=True as well, your database should complain if you tried to enter a blank value. If your foreign key field can take null values, it will return None on null, so to check if it was "left blank", you could simply check if the field is None . What's the difference between is None and if not ?

What is Queryset in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


1 Answers

The ORM will handle None (cast it to NULL) for you and return a QuerySet object, so unless you need to catch None input the first example is fine.

>>> User.objects.filter(username=None) [] >>> type(_) <class 'django.db.models.query.QuerySet'> >>> str(User.objects.filter(username=None).query) SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."username" IS NULL 
like image 101
Hedde van der Heide Avatar answered Oct 21 '22 03:10

Hedde van der Heide