Django ships a set of database functions in django.db.models.functions — Concat, Upper, Lower, Length, Cast, Substr — that let you join strings, change case, measure length, or cast types right inside the SQL query, instead of pulling data into Python and processing it in a loop. Combined with annotate(), you create computed columns usable immediately in filter() and order_by(). They work best when you need to normalize data for display, search case-insensitively, or sort by a transformed value without touching the original data.
The Problem
A familiar situation: the Author table stores first_name and last_name separately, and the list page needs to show the full name. What many people do is fetch all authors and join the strings in Python:
authors = Author.objects.all()for author in authors: print(f"{author.first_name} {author.last_name}")
That works for a few dozen rows, but with thousands of rows it wastes memory and you cannot filter or sort by the full name — because that column does not exist in the database. Similarly, looking up a user by email case-insensitively is often done with __icontains, which is slow and can return unexpected matches.
The Solution
Import the functions from django.db.models.functions and use them with annotate():
from django.db.models import Valuefrom django.db.models.functions import Concat, Upper, Lower, Length# 1. Join the full name right in SQLauthors = Author.objects.annotate( full_name=Concat("first_name", Value(" "), "last_name"))for author in authors: print(author.full_name) # "Nguyễn Văn A"
Concat takes at least two expressions; fixed strings such as a space must be wrapped in Value(). The full_name column only exists in the queryset — the original data stays untouched.
# 2. Find a user by email, case-insensitivelyemail = "NGUYEN.VANA@example.com"user = Author.objects.annotate( email_lower=Lower("email")).get(email_lower=email.lower())# 3. Filter posts with a long enough title, sort by length descendingposts = Post.objects.annotate( title_len=Length("title")).filter(title_len__gte=10).order_by("-title_len")# 4. Display product codes normalized to uppercaseproducts = Product.objects.annotate(sku_upper=Upper("sku"))
Because these functions translate into real SQL UPPER(), LOWER(), and LENGTH(), the transformation runs at the database layer: a single query, no excess data loaded, and the computed column is immediately usable in filter() or order_by(). Two small notes: Concat needs numbers cast first with Cast("views", CharField()) before joining them; and if one part is NULL, the result can become NULL on PostgreSQL — wrap it in Coalesce to avoid losing data.
Apply It to Your Project
Try it right away in a login form: normalize the email to lowercase when looking it up, so users can log in whether they type capitals or not, instead of forcing them to remember exactly how they typed it at sign-up. In the admin, use Concat to display the full name in list_display without adding a column to the model. And when writing reports, Length quickly filters titles that are too short or too long for editing. The general rule: whenever you are about to write a Python loop just to transform strings after a query, stop and check whether a database function can do it inside the query.
Related Posts
- Django: Replace NULL with a Default Value Right in the Query with Coalesce in 5 Minutes
- Django: Label and Compute by Condition Right in the Query with Case/When — Skip the Python Loop
- Django: Group Stats with values() + annotate() — GROUP BY in a Single Query
Frequently Asked Questions
How are database functions different from processing in Python after the query?
Database functions run at the SQL layer, so they cost a single query and load no excess data into memory. Processing in Python means fetching every row first, then filtering or sorting — slow and RAM-hungry when the data is large.
How do I join a string with a number?
Cast the number to a string first with Cast, for example Concat(Value("Post: "), "title", Value(" ("), Cast("views", CharField()), Value(" views)")). On PostgreSQL, joining a number directly into a string raises a type error, while SQLite casts automatically — easy to miss when testing locally.
Can Lower() in a filter still use an index?
Usually not — the database must compute LOWER() on every row before comparing. That is fine for small tables, but for a column you look up often, such as email, the durable fix is to store an extra normalized column or create a functional index on the LOWER(email) expression.
💬 Have you tried this in your own project? If you hit an error or have a neater way to do it, leave a comment below — I read them all and will add the best ideas to the post.
References
- Django documentation — Database Functions: https://docs.djangoproject.com/en/6.1/ref/models/database-functions/
- Django documentation — Query Expressions: https://docs.djangoproject.com/en/6.1/ref/models/expressions/
