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?

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'>
>>> print 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

Need Your Help

fullcalendar unbind the eventClick method for the clickable icons placed on the events

javascript jquery jquery-ui jquery-plugins fullcalendar

I am using fullcalendar plugin. I had used the jquery .on() function to make the icons clickable but the issue is when I click on the icons that are placed on the events then the eventClick method ...

Keeping CPU Usage Low for a certain amount of time. c#

c# cpu-usage performancecounter

I have the following code which only allows my application to open after the CPU Usage is below a certain amount of time. But I just need some help adding something that makes sure the usage stays ...