Filter for Empty or Null Values in Django

Subscribe to my newsletter and never miss my upcoming articles

Django features a great many methods or custom methods, functions to simplify the most complicated tasks so that developers 🙈 can focus on writing applications that work instead of creating methods.

In the recent back, I came across fetching the null and empty value or both from the Django model so the tutorial is all about this only.


We already know that using filter() and exclude() we can retrieve modified Queryset.

Filtering Null Fields

We can use potential field lookup that can be used with filter() and exclude() where the choice should be isnull.

Let's suppose we want to retrieve all the Lead() where the lead is not assigned to anyone.

>> Lead.objects.filter(assigned_to__isnull=True).count()

You see, how quickly we determined that 17 leads are not assigned to anyone.

Filtering Empty Fields

Filtering empty fields means, the field not null but the value is empty otherwise. We can use exact() field lookup.

Let's suppose we want to retrieve the name of Lead with an empty description or email.

>> Lead.objects.filter(lead_description__exact='').count()

We quickly retrieved that 10 fields have no description.

Combining Both filters

One final example is that it is possible to combine multiple field lookups by chaining together filter() or exclude() calls.

Here in this, we are going to fetch a number of fields with empty descriptions and not assigned to anyone.

>> Lead.objects.exclude(assigned_to__isnull=True).exclude(lead_description__exact='').count()

There we have it. Simple and pure uses of filter() and exclude() to retrieve (or ignore) or both values in Django QuerySets.

If you have anything in mind, please let me know in the comment.

Comments (1)

Verbe Rage's photo

Impressive Blog, Cheers