Order Empty Strings Last in Django QuerySets
When ordering a Django QuerySet, you might want rows with empty values to appear last. With NULL values, you’d use nulls_last=True—but CharFields typically store empty strings, not NULL.
The Problem
Django’s documentation recommends avoiding null=True for string-based fields. Empty values should be stored as empty strings "", not NULL.
But nulls_last=True only works with actual NULL values:
# This won't push empty strings to the end
queryset.order_by(F("title").asc(nulls_last=True))The Solution
Use NullIf to convert empty strings to NULL for ordering purposes:
from django.db.models import Value
from django.db.models.functions import NullIf
queryset.order_by(
NullIf("title", Value("")).asc(nulls_last=True),
"name",
)NullIf("title", Value("")) returns NULL when the title equals an empty string, otherwise returns the title. Combined with nulls_last=True, empty titles sort to the end.
How It Works
The NullIf function takes two arguments and returns NULL if they’re equal:
NullIf(expression, Value(""))
# Returns NULL if expression == ""
# Returns expression otherwiseThis only affects the ordering—your actual data stays unchanged as empty strings.