Django's Object-Relational Mapper (ORM) allows developers to interact with database records entirely using Python syntax instead of writing raw SQL. Understanding how QuerySets are constructed, filtered, and evaluated is fundamental to building high-performance web applications.
| Lookup Operator | Django Python Syntax | SQL Translation |
|---|---|---|
exact / iexact |
Post.objects.filter(slug__iexact='django-orm') |
WHERE UPPER(slug) = UPPER('django-orm') |
contains / icontains |
Post.objects.filter(title__icontains='tutorial') |
WHERE title ILIKE '%tutorial%' |
gt / gte |
Post.objects.filter(reading_time__gte=10) |
WHERE reading_time >= 10 |
lt / lte |
Post.objects.filter(price__lt=50.00) |
WHERE price < 50.00 |
in |
Post.objects.filter(id__in=[1, 4, 9]) |
WHERE id IN (1, 4, 9) |
range |
Post.objects.filter(created_at__range=(start, end)) |
WHERE created_at BETWEEN start AND end |
isnull |
Post.objects.filter(published_at__isnull=True) |
WHERE published_at IS NULL |
QuerySets are chainable — applying a filter returns a new QuerySet, allowing you to combine criteria dynamically without firing multiple queries:
# None of these statements hit the database yet! (Lazy evaluation)
posts = BlogPost.objects.filter(is_published=True)
posts = posts.filter(category__name='Technology')
posts = posts.exclude(author__user__username='spammer')
posts = posts.order_by('-created_at')[:10] # LIMIT 10
# Database is hit RIGHT HERE when we iterate over the queryset:
for post in posts:
print(post.title)
A QuerySet is evaluated when: 1) It is iterated over (for obj in qs:), 2) It is sliced with a step (qs[::2]), 3) Sized with len(qs) or converted with list(qs), or 4) Evaluated in a boolean test (if qs:).
Broaden your backend architecture, REST API design, and production engineering expertise:
Build complex OR/AND queries and atomic in-database calculations.
Encapsulate frequently used query filters into reusable manager methods.
Feed querysets into ListView and DetailView classes.
Quick reference table of all ORM lookup operators and methods.