Skip to content
devtoolbox.cc

Django · Chapter 5 of 8

Django QuerySets: filter, lookups, aggregates and transactions

13 min study · Examples checked with Django 6.1 on Python 3.14 ·

With the Lesson model in place, the next step is reading and changing data. Django’s ORM turns Python method calls into SQL: Lesson.objects.filter(published=True) becomes a SELECT ... WHERE published = True. This chapter covers the query API you will use every day, shows when queries actually run, and finishes by switching the catalog’s views from the dictionary to the database. The examples can be tried in python manage.py shell, which opens Python with the project loaded and the models imported.

Create and fetch objects

from catalog.models import Lesson

Lesson.objects.bulk_create([
    Lesson(title="Variables", minutes=20, published=True),
    Lesson(title="Loops", minutes=25, published=True),
    Lesson(title="Decorators", minutes=40, level="advanced", published=True),
    Lesson(title="Metaclasses", minutes=55, level="advanced"),
])

Lesson.objects.count()                      # 4
Lesson.objects.get(title="Loops").minutes   # 25
Lesson.objects.get(title="Generators")      # raises Lesson.DoesNotExist
lesson, created = Lesson.objects.get_or_create(title="Generators", defaults={"minutes": 30})

objects is the model’s manager, the entry point for queries. create(**fields) inserts one row, bulk_create many in one query. get returns exactly one object and raises DoesNotExist if there is none or MultipleObjectsReturned if there are several, so use it for unique lookups such as the primary key. get_or_create returns the object and whether it was created; defaults only applies when creating. Calling it again for “Generators” returns the existing lesson with created false.

Filter with field lookups

short = Lesson.objects.filter(published=True, minutes__lte=30)
print(short)   # <QuerySet [<Lesson: Loops>, <Lesson: Variables>]>

Lesson.objects.filter(title__icontains="LOOP").exists()        # True
Lesson.objects.exclude(published=True).values("title", "minutes")
# <QuerySet [{'title': 'Metaclasses', 'minutes': 55}]>

from django.db.models import Q
Lesson.objects.filter(Q(level="advanced") | Q(minutes__lt=21)).values_list("title", flat=True)
# <QuerySet ['Decorators', 'Metaclasses', 'Variables']>
Lesson.objects.order_by("-minutes").first()                     # <Lesson: Metaclasses>

Keyword arguments combine with AND. A double _ adds a lookup to a field name: __lte, __gte, __lt, __gt, __in, __range, __isnull, __icontains (case-insensitive substring), __startswith, and date parts such as __year. exclude negates a condition, Q objects combine conditions with | (OR), & and ~ (NOT), and order_by("-minutes") sorts descending. The results above are alphabetical because the model’s Meta.ordering applies when you don’t order explicitly.

values() returns dictionaries and values_list() tuples, or plain values with flat=True; both fetch only the columns you name, which is cheaper when you don’t need whole objects. exists() and count() ask the database a yes/no or how-many question instead of loading rows. print(short.query) shows the generated SQL, handy when a result surprises you.

QuerySets are lazy

Building a QuerySet doesn’t touch the database. Each filter, exclude or order_by returns a new QuerySet that only describes a query. The query runs when you need the results: when iterating, calling list(), len() or bool(), slicing with a step, or printing. After that, the QuerySet caches its rows. Measured with Django’s query capture, building Lesson.objects.filter(published=True).order_by("minutes") ran 0 queries, and looping over it twice ran 1.

Laziness lets a view build a query step by step, adding filters only when parameters are present, and still send a single query. The cache has one trap: calling Lesson.objects.filter(...) again creates a new QuerySet and a new query, so keep the QuerySet in a variable when you use it twice. Slicing ([:50]) becomes LIMIT 50, so pagination happens in the database.

Aggregate, annotate and update in the database

from django.db.models import Avg, Count, F, Sum

Lesson.objects.aggregate(total=Sum("minutes"), average=Avg("minutes"))
# {'total': 140, 'average': 35.0}
Lesson.objects.values("level").annotate(n=Count("id"), minutes=Sum("minutes")).order_by("level")
# [{'level': 'advanced', 'n': 2, 'minutes': 95}, {'level': 'beginner', 'n': 2, 'minutes': 45}]
Lesson.objects.filter(level="beginner").update(minutes=F("minutes") + 5)   # 2 rows updated

aggregate computes summary values over a whole QuerySet and returns a dictionary. annotate adds a computed value to each row or, after values(), to each group: the SQL GROUP BY. update changes all matching rows in one UPDATE statement without loading them, and F("minutes") refers to the column’s current value, so the arithmetic happens inside the database. Reading a value into Python, adding to it and saving it back would lose updates when two requests do it at once; F avoids that race.

Transactions

By default each query commits on its own. When several changes must succeed or fail together, wrap them in transaction.atomic():

from django.db import IntegrityError, transaction

try:
    with transaction.atomic():
        Lesson.objects.filter(title="Loops").update(published=False)
        Lesson.objects.create(title="Variables", minutes=10)   # duplicate title
except IntegrityError:
    pass

Lesson.objects.get(title="Loops").published   # True: the update was rolled back

The second statement violates the unique constraint, so the whole block rolls back and “Loops” stays published. Catch the exception outside the atomic block, as here, never inside it. atomic also works as a decorator for a whole view, and the ATOMIC_REQUESTS database setting wraps every request in one. For rare cases the ORM can’t express, Lesson.objects.raw("SELECT ... WHERE minutes > %s", [40]) runs your SQL; always pass values as parameters, never with string formatting.

Use the database in the views

In catalog/views.py, delete the LESSONS dictionary, import Lesson, Sum and get_object_or_404, and replace the three reading views:

@require_GET
def home(request):
    lessons = Lesson.objects.filter(published=True)
    context = {
        "heading": "All lessons",
        "lessons": lessons,
        "total_minutes": lessons.aggregate(total=Sum("minutes"))["total"] or 0,
    }
    return render(request, "catalog/home.html", context)


@require_GET
def lesson_list(request):
    lessons = Lesson.objects.filter(published=True)
    level = request.GET.get("level") or request.COOKIES.get("level")
    if level:
        lessons = lessons.filter(level=level)
    if query := request.GET.get("q", "").strip():
        lessons = lessons.filter(title__icontains=query)
    rows = lessons.values("id", "title", "minutes", "level")[:50]
    return JsonResponse({"lessons": list(rows)})


@require_GET
def lesson_detail(request, lesson_id):
    lesson = get_object_or_404(Lesson, pk=lesson_id, published=True)
    return JsonResponse({"id": lesson.pk, "title": lesson.title, "minutes": lesson.minutes})

Each view builds its query step by step and only adds filters that apply, and the [:50] slice becomes a LIMIT. get_object_or_404 replaces the manual 404 check, and including published=True in its lookup keeps drafts from being reachable by guessing IDs. The templates from chapter 3 work unchanged with model objects, because lesson.title reads attributes the same way it read dictionary keys. Add some lessons through the admin to see them.

Practice

Write a query that lists, for each level, the number of published lessons and their average length, sorted by average descending. Then add a GET /lessons/?max= parameter to lesson_list that keeps lessons up to that many minutes and answers 400 for a value that isn’t a whole number.

Answer check: Lesson.objects.filter(published=True).values("level").annotate(n=Count("id"), avg=Avg("minutes")).order_by("-avg"). In the view, convert with int() inside try/except ValueError and return JsonResponse({"error": ...}, status=400); then lessons = lessons.filter(minutes__lte=limit) before the slice. Check print(lessons.query) to confirm the filter is in the SQL.

Summary

objects.create, get, filter, exclude and order_by cover most reads and writes, with double-_ lookups and Q for complex conditions. QuerySets are lazy and cache their results, so build them step by step and reuse variables. Let the database aggregate, annotate and update with F, group related changes in transaction.atomic(), and use get_object_or_404 in views.

All Django chapters