How to Filter Empty or NULL Values in a QuerySet in Django

Django is powerful and popular web framework for Python that comes with built-in Object-Relational Mapping (ORM) system. One common task when working with databases in Django is filtering QuerySets to retrieve only the records that meet certain criteria. In some cases, you may need to filter out records with empty or NULL values in specific fields. In this blog post, we will explore how to achieve this using Django ORM.

Understanding Empty and NULL Values

Before diving into the code, it’s important to understand the difference between empty and NULL values in a database. An empty value typically refers to field that has no data or contains an empty string ('') or equivalent. On the other hand, NULL represents the absence of a value, and it is not the same as an empty string or zero.

Filter or Find Empty Values in Queryset

To filter out records with empty values in specific field, you can use the __exact lookup with an empty string. Here’s an example:

from myapp.models import MyModel

# Filter records where the 'field_name' is empty
result = MyModel.objects.filter(field_name__exact='')

In this example, replace MyModel with the name of your model and field_name with the name of the field you want to filter. The __exact lookup ensures an exact match with an empty string.

Filtering NULL Values

Filtering out NULL values is straightforward in Django. You can use the __isnull lookup to target fields with NULL values. Here’s an example:

from myapp.models import MyModel

# Filter records where the 'field_name' is NULL
result = MyModel.objects.filter(field_name__isnull=True)

in this code will return records where the specified field is NULL. Make sure to replace MyModel with your actual model name and field_name with the name of field you want to filter.

Combining Filters in Django Queryset

You can also combine filters to retrieve records that meet multiple criteria. For instance, if you want to retrieve records where a field is empty or NULL, you can use the Q object to create an OR condition:

from django.db.models import Q
from myapp.models import MyModel

# Filter records where the 'field_name' is empty or NULL
result = MyModel.objects.filter(Q(field_name__exact='') | Q(field_name__isnull=True))

In this example, we use the Q object to create a logical OR condition between two filters. This allows us to retrieve records where the field is either empty or NULL.

Conclusion

Filtering empty or NULL values in a QuerySet in Django is common task when working with databases. By using the __exact and __isnull lookups, you can easily retrieve the records that meet your criteria. Additionally, you can combine filters with Q object to create more complex conditions. Understanding these techniques will help you efficiently query your database and retrieve the data you need for your Django applications.