How to Filter Empty or NULL Fields in Django QuerySet?
Last Updated :
02 Sep, 2024
When working with a Django project, we often need to filter records where certain fields are either empty or NULL
. This is a common requirement, especially when dealing with user-generated data where fields might be left blank. In Django, we can filter a QuerySet where a specific field has no value or is explicitly set to NULL
. In this article, we will explain how to filter such fields in a Django QuerySet, with examples.
NULL
Values: In a database, a NULL
value signifies the absence of a value. In Django, we can allow a field to store NULL
by setting null=True
in the model definition.
Empty Fields: An empty field, represented as an empty string ('
'),
contains a value, but that value is a string with zero characters.
Filtering Record based on Empty or NULL Fields in Django
Before we start filtering let’s consider a Django model Person
with three fields: first_name
, middle_name
, and last_name
. The middle_name
field can be NULL
or an empty string:
Python
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=100)
middle_name = models.CharField(max_length=100, null=True, blank=True)
last_name = models.CharField(max_length=100)
def __str__(self) -> str:
return f'{self.first_name}_{self.middle_name}_{self.last_name}'
Assume we have the following Person
records:
ID | First Name | Middle Name | Last Name |
---|
1 | Arun | Kumar | Yadav |
2 | Meera | '' | Pathak |
3 | Suraj | NULL | Kumar |
4 | Satyam | '' | Singh |
Add data to the database:
>>> from myapp.models import Person
>>> Person.objects.create(first_name="Arun", middle_name="Kumar", last_name="Yadav")
<Person: Person object (1)>
>>> Person.objects.create(first_name="Meera", middle_name="", last_name="Pathak")
<Person: Person object (2)>
>>> Person.objects.create(first_name="Suraj", middle_name=None, last_name="Kumar")
<Person: Person object (3)>
>>> Person.objects.create(first_name="Satyam", middle_name="", last_name="Singh")
<Person: Person object (4)>
>>>
Now let's start filtering records.
1. Filtering for NULL
Values
To filter records where the middle_name
field is NULL
, we can use the __isnull lookup operation.
For Example: This will return all Person
objects where middle_name
is NULL
.
null_middle_names = Person.objects.filter(middle_name__isnull=True)
Output
<QuerySet [<Person: Suraj_None_Kumar>]>
Filtering for null valuesHere, Suraj is the only person whose middle_name is None.
2. Filtering for Empty values:
To filter records where the middle_name
field is an empty string (''
), we can use a simple equality check (middle_name
=''). Or we can also use iexact and exact lookups to carry out the same operation.
Example: This will return all Person
objects where middle_name
is an empty string.
empty_middle_names = Person.objects.filter(middle_name='')
or
empty_middle_names = Person.objects.filter(middle__exact='')
or
empty_middle_names = Person.objects.filter(middle__iexact='')
Output
<QuerySet [<Person: Meera__Pathak>, <Person: Satyam__Singh>]>
Here, Satyam and Meera has middle_name=''. Also, all three approach gives the same result.
Filtering for Empty Values3. Filtering for Both NULL and Empty Value
If we want to filter records where the middle_name
field is either NULL
or an empty string, we can combine two filters using Q
objects and the |
(OR) operator:
For Example: This query will return all Person
objects where the middle_name
field is either NULL
or an empty string.
null_or_empty_middle_names = Person.objects.filter(middle_name__isnull=True) | Person.objects.filter(middle_name='')
or
null_or_empty_middle_names = Person.objects.filter(Q(middle_name__isnull=True) | Q(middle_name=''))
Output:
<QuerySet [<Person: Meera__Pathak>, <Person: Suraj_None_Kumar>, <Person: Satyam__Singh>]>
Here, Satyam, Meera and Suraj has middle_name withe EMPTY or NULL.
Filtering for Both Empty or NullConclusion
Filtering for NULL
or empty fields in Django is a simple process using the Django ORM. Whether we need to check for missing data, validate form submissions, or perform data migrations, knowing how to filter these fields is crucial. By understanding and applying the isnull
lookup, equality checks, and Q
object combinations, we can efficiently manage our data and ensure our queries return exactly what you need.
Similar Reads
How to do a not equal in Django queryset
In Django, filtering data from the database is typically done through QuerySet methods provided by Djangoâs ORM (Object Relational Mapping). When you need to filter records where a certain field is not equal to a specific value, Django offers an elegant way to handle this using the exclude() method
4 min read
How to perform OR, AND and NOT in Django QuerySet Filtering
We can use the Q objects in django.db.models to create an OR, AND, and NOT filter in a Django query. The Q objects are used to form complex filtering by joining several conditions through logic operators like OR, AND, and NOT. In this article, we will learn to perform AND, OR, and NOT filters while
4 min read
How to Dynamically Compose an OR Query Filter in Django
Djangoâs Object-Relational Mapping (ORM) provides developers with a powerful and intuitive way to interact with databases using Python code. One of the advanced features of Django's ORM is the ability to create complex query filters, including OR queries. These are essential when you need to retriev
6 min read
How to Perform Query Filtering in Django Templates
Sometimes we may want to filter or modify the list of objects within the template itself to tailor the data being displayed. While filtering should generally be done at the view level for clarity and separation of concerns, Django templates provide some basic filtering capabilities through template
5 min read
How to get GET request values in Django?
Django, a high-level Python web framework, simplifies the process of web development. One common task in web applications is handling GET requests, which are typically used to retrieve data from a server. In this article, we'll create a small Django project that displays a message using data from a
2 min read
How to Get a List of the Fields in a Django Model
When working with Django models, it's often necessary to access the fields of a model dynamically. For instance, we might want to loop through the fields or display them in a form without manually specifying each one. Django provides a simple way to get this information using model meta options. Eac
2 min read
Python Django Queryset Filtering
Django has an inbuilt function for filtering the dataset. But it is lacking in the exclusion of dataset. So for this, we have other 2 solutions to filter out data which not equal to the mentioned dataset. Here, We are going to understand and learn through a mini Django project using Python. Let's cr
4 min read
Checking for Empty QuerySet in Django
In Django, the QuerySet is one of the most powerful features of the framework, allowing us to interact with the database by fetching, filtering, and modifying data. However, there are times when we need to determine whether the result of a QuerySet is empty. This is essential for handling scenarios
3 min read
How to combine multiple QuerySets in Django?
QuerySets allow you to filter, order, and manipulate data from your database using a high-level Pythonic syntax. However, there are situations where you may need to combine multiple QuerySets into a single QuerySet to work with the data more efficiently. This article will explore various methods to
5 min read
How to Query For Is Not Null in MongoDB in a Specific Field?
MongoDB with its flexible document-oriented structure, offers powerful querying capabilities to extract meaningful insights from your data. One common requirement in database querying is to retrieve documents where a specific field is not null. In this article, We will learn about How to Query For I
4 min read