How to Use __isnull in Django Querysets
In Django, use the
__isnull lookup in queryset filters to check if a field is null or not. For example, Model.objects.filter(field__isnull=True) returns records where field is null, and field__isnull=False returns records where it is not null.Syntax
The __isnull lookup is used in Django queryset filters to test if a field's value is NULL in the database.
field__isnull=True: Matches records wherefieldisNULL.field__isnull=False: Matches records wherefieldis NOTNULL.
This lookup works with any nullable field type.
python
Model.objects.filter(field__isnull=True) Model.objects.filter(field__isnull=False)
Example
This example shows how to filter a Django model Book to find books with or without a published_date.
python
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) published_date = models.DateField(null=True, blank=True) # Query for books without a published date unpublished_books = Book.objects.filter(published_date__isnull=True) # Query for books with a published date published_books = Book.objects.filter(published_date__isnull=False) print('Unpublished books:', list(unpublished_books.values('title'))) print('Published books:', list(published_books.values('title')))
Output
Unpublished books: [{'title': 'Draft 1'}, {'title': 'Draft 2'}]
Published books: [{'title': 'Django Basics'}, {'title': 'Advanced Django'}]
Common Pitfalls
Common mistakes when using __isnull include:
- Forgetting to set
null=Trueon the model field, so the database never storesNULL. - Using
__isnullon non-nullable fields, which will always return empty or all results. - Confusing
Nonein Python withNULLin the database;__isnullchecks databaseNULLvalues only.
Wrong:
Model.objects.filter(field__isnull=None) # Incorrect, use True or False
Right:
Model.objects.filter(field__isnull=True)
python
Model.objects.filter(field__isnull=None) # Wrong Model.objects.filter(field__isnull=True) # Correct
Quick Reference
| Usage | Description |
|---|---|
| field__isnull=True | Filters records where field is NULL |
| field__isnull=False | Filters records where field is NOT NULL |
Key Takeaways
Use
field__isnull=True to find records where a field is NULL in the database.Use
field__isnull=False to find records where a field has a value (not NULL).Ensure the model field has
null=True to store NULL values in the database.Never pass None to
__isnull; always use True or False.This lookup works with any nullable field type in Django models.