Chapter 19 · ORM fundamentals: saving and finding eventsCHAPTER 19
Complete six-part pre-release for review. Public pages show published events only; drafts and cancelled events return 404 until the publication workflow in Chapter 26.
Working towards: First release (Chapter 34). One community runs free events. Members sign up, register, see, and cancel their registrations; organizers publish their own events; two people cannot both take the last place. Tests check each product rule. All milestones
CHAPTER NINETEEN
ORM fundamentals: saving and finding events
Stage 3: Data and the database (Chapters 15 to 23)
Prerequisites: Chapters 4, 9 to 12, and 15 to 18, including the Chapter 18 project, its 29 passing tests, its applied migrations, and its empty events_event table
What you’ll build: Three events saved, found, changed, and deleted in the Django shell, and event pages that read published events from the database, proved by tests that count their queries and hide drafts.
Why This Matters
Sam has a meetup to announce. It is on Thursday 19 November at Leeds Central Library, and he wants it on Otahque’s events page. He is also writing a plan for a spring event, which nobody should see until it is ready. Since Chapter 11, the events page has listed one fictional event from a Python dictionary, with a “Sample” label to say so. Chapter 18 created the event table, and it is still empty. Nothing connects the page to the table.
Soni has a different question. The online Django workshop is run from India, and she wants to know when it starts there, in the time its organizers chose, not in the server’s time. The event table stores every start time in one standard zone, UTC, and stores each event’s own zone beside it, as the Chapter 15 ERD asked. Something has to read both and show the right local time.
This chapter teaches Django’s ORM, its object-relational mapper, the part of Django that saves, finds, changes, and deletes rows through Python objects. You use it first in the Django shell, with three events of your own, and then in the views, which stop reading the dictionary. The public pages show published events only: a draft’s address returns “404 Not Found”. Tests prove that rule, the order of the list, the local time, and the number of database queries the list page runs.
By the end of the chapter, you will be able to:
explain what a manager and a QuerySet are, and use Event.objects to create, read, change, and delete rows in the Django shell;
choose between get() and filter(), and handle the errors each can raise;
narrow, exclude, order, slice, and count results with field lookups such as title__icontains and starts_at__gte;
say when a QuerySet runs its query, when it reuses its results, and how to count the queries something runs;
explain why save() does not check a row’s values, and what update() skips;
write views and tests that read published events from the database and hide everything else.
This chapter works with one model, Event, and only with rows you type in yourself. Relationships between tables, such as registrations, arrive in Chapter 20. Validation rules and database constraints are Chapter 21. Combining conditions with Q and F, counting with aggregation, and named query methods such as published() are Chapter 22. The admin site, the administrator’s tool for checking and correcting data, is Chapter 23, and forms are Chapter 24. Organizers will manage their own events on Otahque’s pages, from Chapter 26. Publishing an event through the product’s own workflow, and deciding what visitors see when an event is cancelled, wait for Chapter 26.
Chapter 15 asked questions of a database in SQL, and Chapter 16 described the event table as a Python class. A program needs both at once: it thinks in objects, and the database stores rows.
New Concept: the ORM
What problem exists? Python code works with objects that have attributes, such as event.title. The database stores rows in tables and answers SQL. Every page that shows events has to turn a question into SQL, send it, and turn each row it receives back into something Python can use.
What did people do before? They wrote the SQL by hand in each view, often building it out of strings, and copied each column out of each row by position. Every query was a chance to misspell a column, forget a condition, or let a visitor’s text change the SQL itself.
What is an ORM? An object-relational mapper translates in both directions. You describe what you want in Python, such as “events whose status is published, soonest first”, and the ORM writes the SQL, sends the values separately from it, and builds one model object for each row. Django’s ORM uses the models you wrote in Chapter 16 to know the tables and columns.
Why use it? The query is written once, in Python, and checked against the model’s fields. The same code runs on SQLite now and PostgreSQL in Chapter 32. Values never become part of the SQL text, which closes the most common route to SQL injection.
Now let’s use it. Every query in this chapter starts from Event.objects.
The ORM does not stop you from writing SQL, and it does not make SQL knowledge useless. Chapter 15’s SELECT, WHERE, and ORDER BY are exactly what the ORM writes for you, and knowing them helps you read what it does. Step 3 shows you that SQL.
Managers and QuerySets
Two words describe almost everything in this chapter.
New Concept: managers and QuerySets
What problem exists? You need a starting point for every question about a table, and a way to refine a question step by step, such as “published events”, then “in Leeds”, then “soonest first”, without running a query at each step.
What did people do before? A query was one string, written all at once. Refining it meant editing the string, or writing a second one.
What are they? A manager is the object on a model class through which queries start. Django gives every model one called objects, so Event.objects is the event table’s manager. Chapter 17 wrote one of its own, UserManager, to add create_user(); most models use Django’s plain one. A QuerySet is a description of a query that has not necessarily run yet. Event.objects.all() returns a QuerySet of every event; filter(), exclude(), and order_by() each return a new QuerySet with one more condition or order, leaving the one they started from unchanged.
Why use them? A QuerySet can be built in steps, passed around, and refined, and it reaches the database only when something needs its rows. The view can build one, and the template can loop over it.
Now let’s use them. Step 3 builds QuerySets in the shell and counts when they run.
A QuerySet behaves like a list in a few ways: you can loop over it, ask its length, and slice it with [:2]. It is not a list, though, and the next topics show where the difference matters.
The Django shell
Saving rows needs Python with Django’s settings loaded. Chapter 16’s practice helper did that for one script at a time; the Django shell does it for a session you type into.
New Tool: the Django shell
What problem exists? You want to try a query and see its answer at once, then try the next one, without writing a file for each.
What did people do before? Chapter 16’s setup_django.py loaded the settings, and each experiment was a script you saved and ran again.
What is the Django shell?manage.py shell starts Python’s interactive prompt with Otahque’s settings loaded. It also imports every model from the installed apps automatically, and, since Django 6.0, a few common tools such as connection, so Event and User are ready without an import line. You type a line after the >>> prompt and press Enter; Python runs it and prints its value. A line that opens a block, such as a for loop, or leaves a bracket open, gets a ... prompt for the next line.
Why use it? It is the quickest way to learn the ORM: every call and its answer are in front of you. Rows you save are saved for real, in your db.sqlite3.
Now let’s use it. Steps 1 to 4 happen in the shell.
In this book, a shell session is printed as you would see it. Type what follows each >>> or ... prompt, and nothing else; the lines without a prompt are what Python prints back. A line that is only ..., after an indented block, means “press Enter on an empty line” to finish the block. Elsewhere, a ... line marks lines left out of a long message, such as the middle of an error’s traceback.
One object or many
Two methods answer questions, and they answer different kinds.
New Concept: get(), filter(), and field lookups
What problem exists? Sometimes you need exactly one event, such as the one whose address a visitor opened. Sometimes you need every event that matches a condition, and there may be none, one, or many.
What did people do before? With SQL, every query returned a list of rows, and each caller checked by hand whether the list had the one row it expected.
What are they?get() returns exactly one object. If no row matches, it raises the model’s DoesNotExist error, such as Event.DoesNotExist; if more than one matches, it raises MultipleObjectsReturned. filter() returns a QuerySet of every match, which may be empty, and never raises either error. Both take conditions as keyword arguments. A plain field name, such as status='published', means “equals”. A field name, two underscores, and a lookup name ask a different question: title__icontains='python' means “the title contains python, ignoring letter case”, and starts_at__gte=... means “starts at or after”.
Why the difference? A page about one event needs one event, or a clear “not found”. A list page needs a collection that may be empty. Choosing the method states what you expect, and the errors catch the cases you did not expect.
Now let’s use them. Steps 2 and 3 try both, including the errors.
Table 19.1 lists the lookups this chapter uses. Django has many more, listed in its QuerySet reference; these cover most everyday pages.
Table 19.1 — Field lookups used in this chapter
Lookup
Example
Meaning
exact (the default)
status='draft'
Equal to, letter case included
iexact
title__iexact='python meetup'
Equal to, ignoring letter case
icontains
title__icontains='plan'
Contains, ignoring letter case
gte, lt
starts_at__gte=december
At or after; before
year
starts_at__year=2027
In that calendar year (in UTC here)
in
status__in=[...]
Equal to any value in the list
One difference between databases matters already. On SQLite, contains, the case-sensitive form of icontains, also ignores letter case for English letters, because SQLite’s LIKE does. Use icontains when you mean “ignoring case”, so that the query means the same thing on PostgreSQL in Chapter 32.
When a query runs
A QuerySet is lazy: building it costs nothing, and the database is asked only when something needs the rows.
Under the Hood: laziness and the result cache
Event.objects.filter(...) creates a QuerySet object holding a description of the query, Django’s own Query object, and returns at once; no SQL is sent. Each filter(), exclude(), or order_by() copies that description and adds to the copy. The query runs when the QuerySet is evaluated: when a for loop starts, when list(), len(), or bool() is called on it, when the shell prints it, or when a template’s {% for %} loops over it. At that moment Django turns the description into SQL for the database in use, sends it with the values as separate parameters, builds one model object per row, and stores the list of objects inside that QuerySet, its result cache. Looping over the same QuerySet again uses the cache. So do count() and exists() once the whole result is cached, because the answer is already known. A new QuerySet, even one built from the same code, starts with an empty cache and queries again. Two details are easy to miss. Slicing, such as [:2], and taking one item, such as [0], on a QuerySet that has not been evaluated return a new query each time instead of filling the cache. And calling count() or exists() on a QuerySet that has not been evaluated asks the database a smaller question, SELECT COUNT(*), without loading any rows.
One QuerySet’s path, from the manager to the reused cache, is drawn in Figure 19.1.
Figure 19.1 — A QuerySet is built without a query, evaluated once, and reused.
Laziness is why a view can build a QuerySet and hand it to a template without running anything, and why the list page can run exactly one query however many events it shows. It is also why a careless loop can run many: each time code builds a new QuerySet inside a loop, it asks the database again. Step 3 counts both cases, and the list page’s test pins the count at one.
Try it yourself
Que. 1 Raj builds a QuerySet of the published events and names it upcoming. On the next line, he calls order_by() on it to sort the events latest first, and gives the result the same name. How many queries have run after the two lines, and what did the second line do to the first QuerySet?
Flip to check your answerFold answer back
Answer. None. Both lines build QuerySets; nothing has asked for rows yet. The second line does not change the first QuerySet: order_by() returns a new QuerySet with the same condition and a new order, and the name upcoming now refers to that new one. The query runs when something evaluates it, such as a loop.
Changing and deleting rows
Reading is half the job. The ORM changes rows in two ways, and neither checks the values.
Table 19.2 — Ways to change and delete rows
Call
What it sends
Use it when
obj.save()
One UPDATE of every column, or an INSERT for a new object
You changed one object in Python
obj.save(update_fields=[...])
One UPDATE of the named columns only
Only those fields changed
qs.update(field=value)
One UPDATE for every matching row
Many rows get the same new value
obj.delete(), qs.delete()
DELETE of the object, or every matching row
Rows should go
update() works in the database only. It does not call any model’s save(), it does not change objects you already hold in Python, and it returns the number of rows it matched. delete() returns how many rows it deleted, with a count per model.
Common Error: assuming save() checks the data
Chapter 16 called full_clean() and saw Django refuse a status of archived. That check does not run when you save: save() sends whatever the object holds, and the database stores it unless a database rule refuses it. Django’s documentation says full_clean() is not called automatically by save(). Forms call it for you, from Chapter 24, and Chapter 21 adds database constraints, which refuse bad values however they arrive. Step 4 saves a broken row on purpose, sees it stored, and deletes it.
Public pages and the published rule
The pages read the database from Step 6. What they read is a product decision: the PRD’s requirement that drafts stay hidden from visitors becomes a condition in a query.
Prefer get() with a try block in a view?
A detail view could call Event.objects.get(pk=event_id) inside try, catch Event.DoesNotExist, and raise Http404, as Chapter 10’s view did for the dictionary. get_object_or_404(), from django.shortcuts, does exactly that in one call: it takes a model, a manager, or a QuerySet, and the same conditions as get(), and raises Http404 when nothing matches. Use it in views, where “not found” should become a 404 page. Outside views, such as in the shell or a script, use get() and catch the named error, so that a missing row is not mistaken for a missing page. Never catch a bare Exception around get(): it would hide a typo in a field name as easily as a missing row.
The detail view needs the published rule too, not only the list. If it looked events up by id alone, anyone who guessed /events/3/ would see the spring plan. Figure 19.2 shows both pages’ path.
Figure 19.2 — The events pages read published rows only; a draft never reaches a template.
In practice: a page that must never show drafts
Situation. An organizer saves a half-written event to come back to later. Its title mentions a speaker who has not yet agreed. If it appears on a public page, even for an hour, the community sees it.
Application. The rule lives in the query, filter(status=Event.Status.PUBLISHED), in every view that serves visitors, and a test proves it for each page by saving a draft and asserting that it does not appear. A template that hides drafts with an {% if %} would still load them, and would forget the rule on the next page someone writes.
Consideration. Writing the same condition in two views is repetition that can drift: a third view may forget it. Chapter 22 moves the rule into one named method, published(), after you have seen the repetition it removes. Until then, the tests are the guard.
Start from Chapter 18, in the folder containing manage.py, with your own .env, the locked environment, 29 passing tests, every migration applied, and a local superuser. The events_event table is empty. Steps 1 to 4 work in the Django shell and change only rows in db.sqlite3: you save three events and leave two of them published and one a draft. Steps 5 and 6 change files: the event tests, the views, and the two event templates in the events app, and the stylesheet source in static/otahque. They also delete the app’s templatetags folder and rebuild the stylesheet. At the end of Step 7, 30 tests pass, /events/ lists the two published events soonest first, the workshop’s page shows its start time in India, the draft’s address returns 404, and the work is committed.
The Custom Way
This illustration asks SQLite for published events by building the SQL out of a string, as hand-written database code often did; do not add it to the project. It uses a small table in memory, so it runs anywhere:
illustration_only/string_sql.py (not part of the project)
import sqlite3
db = sqlite3.connect(':memory:')
db.execute('CREATE TABLE event (title TEXT, status TEXT)')
db.executemany('INSERT INTO event VALUES (?, ?)', [
('Python meetup', 'published'),
('Spring planning', 'draft'),
])
def titles(sql, params=()):
return [t for (t,) in db.execute(sql, params)]
status = "published' OR '1'='1"
built = f"SELECT title FROM event WHERE status = '{status}'"
print('built:', titles(built))
safe = 'SELECT title FROM event WHERE status = ?'
print('placeholder:', titles(safe, (status,)))
print('normal:', titles(safe, ('published',)))
The status value stands for text that came from outside the program, such as part of a web address. Built into the SQL with an f-string, its quote mark ends the string early, and OR '1'='1' becomes part of the condition, which is true for every row: the draft leaks. This is SQL injection. The second query uses a ? placeholder and passes the value separately, so SQLite compares the status with the whole text, quote marks and all, and finds nothing; with a real status it works normally. Now list what the hand-written version still lacks even when it uses placeholders: each query names its columns by hand, each row comes back as a tuple to unpack by position, nothing checks that status is a real column, and the SQL would need rewriting for another database.
Under the Hood: how the ORM sends values
When the ORM turns filter(status=...) into SQL, the SQL holds a placeholder, and the value travels beside it as a parameter, exactly like the illustration’s ?. The database never reads the value as SQL. This is why ORM queries are protected from SQL injection by default. The protection ends where you build SQL text yourself: an f-string passed to a cursor, raw() with values joined into its text, or the old extra() method. Injection is category A05 in the OWASP Top 10 2025, a widely used list of the most serious web application risks, and SQL injection is one of its main forms. Chapter 55 uses raw() safely, with parameters, and Chapter 59 reviews injection across the whole application.
The Django Way
Seven steps follow. Steps 1 to 4 use the shell; Steps 5 to 7 change files, tests first.
Step 1: Check the starting point
Run every test, beside manage.py, in PowerShell, Git Bash, a macOS shell, or Linux/WSL Bash:
Terminal
uv run python manage.py test
Expected result, shortened with ...:
Output
Found 29 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.............................
...
Ran 29 tests in ...
OK
Destroying test database for alias 'default'...
Check that the event table’s migration is applied to your database:
Terminal
uv run python manage.py showmigrations events
Output
events
[X] 0001_initial
Now start the shell, in any of the four shells:
Terminal
uv run python manage.py shell
Python greets you, then waits at >>>. Ask how many events there are, then for all of them:
Django shell
13 objects imported automatically (use -v 2 for details).
Python 3.14.9 ...
Type "help", "copyright", "credits" or "license" for ...
(InteractiveConsole)
>>> Event.objects.count()
0
>>> Event.objects.all()
<QuerySet []>
>>> exit()
now exiting InteractiveConsole...
The first line counts what the shell imported for you; Event is one of the 13. The line after Python 3.14.9 describes your system, so it differs on macOS and Linux. count() asks the database how many rows match, and all() returns a QuerySet of every row; printed, an empty one is <QuerySet []>. exit() leaves the shell and returns you to your terminal. Run uv run python manage.py shell -v 2 once if you are curious: it lists each automatic import, then starts the shell as usual.
If count() fails with no such table: events_event, migrate has not run on this database; run uv run python manage.py migrate, which applies only what is missing. If the shell says name 'Event' is not defined, you started plain python, or shell with --no-imports; leave with exit() and start it as shown. If count() prints a number above zero, rows are left from an experiment of your own. Keep them: the pages will list them too, and the rest of the chapter works the same.
Step 2: Create events and fetch them
Start the shell again with uv run python manage.py shell, and import Python’s datetime and UTC, which the shell does not import for you. Then build Sam’s meetup as an object and look at it before saving:
Calling the class, Event(...), creates an object in Python only. Its primary key, pk, the id column, is None, because the database has not seen it, and its status is the model’s default, draft. save() sends an INSERT, and the database chooses the id. starts_at is an aware datetime: tzinfo=UTC says which zone the 18:30 belongs to, and so is ends_at. Otahque stores every start and end time in UTC and the event’s own zone, here Europe/London, beside it.
Common Error: a naive datetime
Leave out tzinfo=UTC, and save() still works but prints RuntimeWarning: DateTimeField Event.starts_at received a naive datetime (2026-11-19 18:30:00) while time zone support is active. A naive datetime has no zone, so Django guesses that it means the default zone in settings.py, UTC. The guess happens to be right here and would be wrong for an event entered in Kolkata time. Delete the row with delete(), shown in Step 4, and create it again with tzinfo=UTC.
create() does both steps at once: it builds the object, saves it, and returns it. Create the online workshop, which Soni wants to attend, already published, and the spring plan as a draft:
Event.Status.PUBLISHED is Chapter 16’s choice, which stores 'published'. The workshop runs from 09:00 to 12:00 UTC, which is 14:30 to 17:30 in India. Loop over every event to see what the table holds. Type the for line, then the indented print line, then press Enter on the empty ... line:
Django shell
>>> for event in Event.objects.all():
... print(event.pk, event.title, event.status)
...
1 Python meetup draft
2 Django workshop published
3 Spring planning draft
The events come back soonest first without asking, because Chapter 16’s model sets ordering = ['starts_at']. Your ids should match these. If you created and deleted events along the way, yours are higher: SQLite does not reuse an id once it has been used. That is why the steps below refer to meetup.pk, never to a number you type.
Common Error: a misspelled field name
Event(titel='Python meetup') fails at once with TypeError: Event() got unexpected keyword arguments: 'titel', and nothing is saved. Check the spelling against events/models.py.
Now fetch one event with get(), then ask for one that does not exist, then for one that is not unique:
The shell prints an event using Chapter 16’s __str__(), its title. The second call asks for Python Meetup with a capital M; an equals condition compares letter case too, so no row matches, and the message ends does not exist. The third matches the two drafts, and the full message is get() returned more than one Event -- it returned 2!. Both errors stop the line, not the shell, which waits at the next >>>. Their full tracebacks name files inside Django; read the last line first. Leave the shell with exit().
Step 3: Ask questions with QuerySets
Start the shell again and import datetime and UTC. Build a QuerySet of the published events, print it, and then exclude the online events:
Django shell
>>> from datetime import UTC, datetime
>>> published = Event.objects.filter(
... status=Event.Status.PUBLISHED
... )
>>> published
<QuerySet [<Event: Django workshop>]>
>>> Event.objects.exclude(location='Virtual')
<QuerySet [<Event: Python meetup>, <Event: Spring planning>]>
>>> Event.objects.filter(status="published' OR '1'='1")
<QuerySet []>
Only the workshop is published so far; the meetup is still a draft until Step 4. exclude() is the opposite of filter(): every row that does not match. The third line is the Custom Way’s attack, given to the ORM. No event has that text as its status, so nothing matches, and the draft stays hidden: the value was sent as a parameter, never as SQL.
iexact finds the meetup that Step 2’s exact get() missed. count() on a QuerySet that has not run asks the database for a number, not for rows, so it is the cheap way to ask “how many”. A datetime you compare with must be aware too, so december has tzinfo=UTC.
Order, slice, and pick one:
Django shell
>>> latest = Event.objects.order_by('-starts_at')
>>> [event.title for event in latest[:2]]
['Spring planning', 'Django workshop']
>>> latest.first()
<Event: Spring planning>
>>> Event.objects.filter(location='Leeds').exists()
False
>>> Event.objects.filter(location='Leeds').first()
>>> Event.objects.filter(location='Leeds')[0]
Traceback (most recent call last):
...
IndexError: list index out of range
order_by('-starts_at') replaces the model’s order; the minus sign means latest first. [:2] becomes SQL’s LIMIT 2, and the list comprehension prints just the titles, which keeps the output short. first() returns the first object, or None when there is none, which is why the shell prints nothing for the empty Leeds search: no location equals Leeds exactly, because the library’s location is Leeds Central Library. exists() answers “is there at least one?” without loading rows. Indexing an empty QuerySet with [0] raises IndexError; use first() when nothing may match.
Two mistakes come up often. Try them both:
Django shell
>>> Event.objects.filter(name='Python meetup')
Traceback (most recent call last):
...
django.core.exceptions.FieldError: Cannot resolve ...
>>> published.title
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'title'
The full first message goes on to list every valid field name after Choices are:. There is no name field; the event’s field is title. The second treats a QuerySet as one event. A QuerySet holds events but has no title of its own; loop over it, or use get() or first() to get one object.
To see roughly what SQL a QuerySet will run, print its query attribute:
Django shell
>>> print(published.query)
SELECT ... WHERE "events_event"."status" = published ...
The full line lists every column in the SELECT, then the WHERE condition, then ORDER BY the start time, from the model’s ordering. Read it as an approximation for people, not as the SQL that runs: published appears without quote marks because the real query sends it separately as a parameter. Django’s documentation does not treat query as part of its public interface, so use it for looking only.
Finally, count queries. CaptureQueriesContext, from Django’s test utilities, records every query run inside a with block; connection is one of the shell’s automatic imports. Type each block, then press Enter on the empty ... line:
Django shell
>>> from django.test.utils import CaptureQueriesContext
>>> with CaptureQueriesContext(connection) as queries:
... in_person = Event.objects.exclude(location='Virtual')
... print('built:', len(queries))
... titles = [event.title for event in in_person]
... print('listed:', len(queries))
... print(in_person.count(), in_person.exists())
... print('reused:', len(queries))
...
built: 0
listed: 1
2 True
reused: 1
>>> with CaptureQueriesContext(connection) as queries:
... print(Event.objects.count(), Event.objects.count())
... print('queries:', len(queries))
...
3 3
queries: 2
These are Figure 19.1’s numbers. Building in_person ran nothing. The list comprehension evaluated it: one query. After that, count() and exists() used its cache: still one. In the second block, Event.objects.count() builds a new QuerySet each time it is written, so writing it twice runs two queries. Leave the shell with exit().
Step 4: Change and remove rows
Sam has two changes. The meetup has moved to Room 2 of the library, and it is ready to publish. Start the shell again and import datetime and UTC. Fetch the meetup by its title, which is unique among your events, change one field, and save only that field:
Django shell
>>> from datetime import UTC, datetime
>>> meetup = Event.objects.get(title='Python meetup')
>>> meetup.location = 'Leeds Central Library, Room 2'
>>> meetup.save(update_fields=['location'])
>>> Event.objects.get(pk=meetup.pk).location
'Leeds Central Library, Room 2'
Changing the attribute changes the object in Python only; save() writes it. With update_fields, the UPDATE sets that one column, so it cannot overwrite a change someone else made to another column in the meantime. Fetching the row again shows what the database holds.
Publish it with update(). Before any update() or delete(), count what the QuerySet matches, so that you know how many rows will change:
update() returned 1, the number of rows it matched. The meetup object still said draft, because update() changed the database, not objects already in Python. refresh_from_db() reloads an object’s fields from its row.
Common Error: update() or delete() on every row
Calling update() on Event.objects itself, or delete() on Event.objects.all(), changes or deletes every event, and the shell has no undo. Build the QuerySet first, check its count(), then call update() or delete() on it, as in this step. If it happens to your practice rows, recreate them with Step 2’s create() calls; never delete db.sqlite3 or a migration to recover.
Now see that save() checks nothing. Save an event that breaks every rule the model describes, then find and delete it:
An empty title, an unknown time zone, no places, and a status that is not one of the three choices: the database stored all of it, because the table’s only rule about these columns is that capacity is not negative. Chapter 16’s full_clean() would have refused the title, the location, and the status, but nothing called it. delete() returned the total number of rows deleted and the count for each model: here one Event. Its id, 4, will not be used again. Check what the table holds now:
Django shell
>>> for event in Event.objects.all():
... print(event.pk, event.title, event.status)
...
1 Python meetup published
2 Django workshop published
3 Spring planning draft
Two published events and one draft: the data the pages will show. Leave the shell with exit(). These rows live in db.sqlite3, which Git ignores, so they are yours alone; a teammate’s copy of Otahque has its own.
Step 5: Write the page tests first
The pages still read the dictionary. Before changing them, change the tests to describe the pages you want. Tests that use the database must be TestCase classes, from Chapter 18, and each class creates its events once in setUpTestData(), a class method that TestCase runs before the class’s tests. Each test then sees those rows, and any change a test makes is rolled back before the next one.
Open events/tests.py. This step replaces everything above class DesignSystemTests with the seven listings below, in order; DesignSystemTests and EventModelTests stay as they are. Start with the imports and two helpers. patch, Context, and Template are no longer needed, and TestCase joins SimpleTestCase:
events/tests.py (1 of 7: imports and helpers)
"""Tests for the events app."""
from datetime import UTC, datetime, timedelta
from pathlib import Path
from django.contrib.staticfiles import finders
from django.core.exceptions import ValidationError
from django.template.loader import render_to_string
from django.test import SimpleTestCase, TestCase
from django.urls import resolve, reverse
from . import views
from .models import Event
def save_event(**changes):
"""Save a published event; keywords replace defaults."""
fields = {
'title': 'Python meetup',
'starts_at': datetime(2026, 11, 19, 18, 30,
tzinfo=UTC),
'timezone': 'Europe/London',
'location': 'Leeds Central Library',
'capacity': 40,
'status': Event.Status.PUBLISHED,
}
fields.update(changes)
fields.setdefault(
'ends_at', fields['starts_at'] + timedelta(hours=2)
)
return Event.objects.create(**fields)
def layout_pages(event):
"""List the pages sharing the layout, for one event."""
return [
('/', 'events/home.html', 'Otahque'),
('/events/', 'events/list.html',
'Events | Otahque'),
(f'/events/{event.pk}/', 'events/detail.html',
'Python meetup | Otahque'),
]
save_event() saves a published event with sensible values, and any keyword argument replaces one of them, so a test states only what matters to it, such as status=Event.Status.DRAFT. When a test gives no end time, setdefault() sets one two hours after the start, so a test that moves the start never leaves the end before it. layout_pages() lists the three pages with their templates and titles; the detail page’s address depends on the saved event’s id, so it is built from the event. Next, the routing tests:
The list test now needs an event in the database. Its title is Django workshop, not Python meetup, on purpose: the old dictionary’s one sample is a Python meetup with id 1, so a test looking for that title at /events/1/ could pass against the old code for the wrong reason. Next, a new class for the list page:
setUpTestData() saves four events: two published, the later one first, one draft, and one cancelled. The first test is the published rule and the order: inside assertNumQueries(1), the page must run exactly one query, whatever it shows. index() finds where each title appears in the page’s HTML, so assertLess proves that the meetup, which starts first, is listed first. assertNotContains proves that the draft and the cancelled event are absent. The second test deletes every event, which is rolled back afterwards, and checks the new empty message. Next, the detail page:
events/tests.py (4 of 7: detail page)
class EventDetailTests(TestCase):
"""One published event by number; 404 for any other."""
@classmethod
def setUpTestData(cls):
cls.event = save_event()
def test_published_event(self):
response = self.client.get(
f'/events/{self.event.pk}/'
)
self.assertContains(
response, '<h1>Python meetup</h1>', html=True
)
self.assertContains(
response, 'Thursday 19 November 2026, 18:30 GMT'
)
self.assertContains(
response, 'Thursday 19 November 2026, 20:30 GMT'
)
self.assertContains(
response, 'Leeds Central Library'
)
self.assertTemplateUsed(
response, 'events/detail.html'
)
def test_time_in_event_time_zone(self):
event = save_event(
starts_at=datetime(2026, 12, 3, 9,
tzinfo=UTC),
timezone='Asia/Kolkata',
)
response = self.client.get(f'/events/{event.pk}/')
self.assertContains(
response, 'Thursday 3 December 2026, 14:30 IST'
)
def test_unpublished_events_are_hidden(self):
response = self.client.get(
f'/events/{self.event.pk}/'
)
self.assertContains(
response, 'Leeds Central Library'
)
for status in (Event.Status.DRAFT,
Event.Status.CANCELLED):
with self.subTest(status=status):
event = save_event(status=status)
response = self.client.get(
f'/events/{event.pk}/'
)
self.assertEqual(response.status_code, 404)
def test_missing_event(self):
self.assertIs(
resolve('/events/999/').func,
views.event_detail,
)
response = self.client.get('/events/999/')
self.assertEqual(response.status_code, 404)
def test_invalid_id(self):
response = self.client.get('/events/abc/')
self.assertEqual(response.status_code, 404)
test_published_event checks the heading, the start and end times, and the location. The meetup starts at 18:30 UTC, and London is on UTC in November, so its time does not change. The second test is the real check of the time zone: the workshop starts at 09:00 UTC, and the page must say 14:30 IST, India Standard Time. The third test is the published rule for the detail page, and it starts by fetching the published event and checking its location, which the old page never shows. Without that first check, the 404s would prove nothing: the old code also returns 404 for both, because neither id is in its dictionary. subTest() reports the draft and the cancelled event separately if either fails. The last two tests are Chapter 10’s, unchanged. Next, escaping, now with saved titles instead of a patched dictionary:
events/tests.py (5 of 7: escaping)
class TemplateSafetyTests(TestCase):
"""Templates escape titles; an empty list says so."""
@classmethod
def setUpTestData(cls):
cls.event = save_event(
title='<strong>Not a tag</strong>'
)
def test_list_escapes_title(self):
response = self.client.get('/events/')
self.assertContains(
response, '<strong>'
)
self.assertNotContains(
response, '<strong>Not a tag'
)
def test_detail_escapes_title(self):
response = self.client.get(
f'/events/{self.event.pk}/'
)
self.assertContains(
response, '<strong>'
)
self.assertNotContains(
response, '<strong>Not a tag'
)
Next, the layout tests, whose page list now comes from layout_pages():
events/tests.py (6 of 7: layout)
class LayoutTests(TestCase):
"""Every page shares the base layout and navigation."""
@classmethod
def setUpTestData(cls):
cls.pages = layout_pages(save_event())
def test_pages_extend_layout(self):
for url, template, title in self.pages:
with self.subTest(url=url):
response = self.client.get(url)
self.assertTemplateUsed(response, template)
self.assertTemplateUsed(
response, 'base.html'
)
self.assertContains(
response, f'<title>{title}</title>',
html=True,
)
def test_pages_include_navigation(self):
for url, template, title in self.pages:
with self.subTest(url=url):
response = self.client.get(url)
self.assertTemplateUsed(
response, 'includes/site_nav.html'
)
self.assertContains(
response,
'<a href="/">Home</a>',
html=True,
)
self.assertContains(
response,
'<a href="/events/">Events</a>',
html=True,
)
Finally, the partial test, which renders one row by itself, and the stylesheet tests. The partial test needs an event with an id, but no database: an unsaved Event(pk=7, ...) has one, so this class stays a SimpleTestCase. The SampleLabelFilterTests class is gone, because Step 6 deletes the filter it tested:
events/tests.py (7 of 7: partial and stylesheet)
class EventRowPartialTests(SimpleTestCase):
"""The event row partial renders one event."""
def test_row_renders_alone(self):
event = Event(pk=7, title='<b>Not a tag</b>')
html = render_to_string(
'events/list.html#event-row', {'event': event}
)
self.assertIn('href="/events/7/"', html)
self.assertIn('<b>Not a tag', html)
self.assertNotIn('<nav', html)
class StylesheetTests(TestCase):
"""Pages link the stylesheet, and Django can find it."""
@classmethod
def setUpTestData(cls):
cls.pages = layout_pages(save_event())
def test_pages_link_stylesheet(self):
for url, template, title in self.pages:
with self.subTest(url=url):
response = self.client.get(url)
self.assertContains(
response,
'<link rel="stylesheet"'
' href="/static/otahque/site.css">',
html=True,
)
def test_finder_locates_stylesheet(self):
self.assertIsNotNone(
finders.find('otahque/site.css')
)
Run every test, with the new tests against the old pages:
Terminal
uv run python manage.py test
Expected result, shortened with ...:
Output
Found 30 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...
FAIL: test_published_event (events.tests.EventDetailTes...
...
FAIL: test_published_events_soonest_first (events.tests...
...
AssertionError: 0 != 1 : 0 queries executed, 1 expected
...
FAILED (failures=10)
Destroying test database for alias 'default'...
Thirty tests, ten failures, and every failure is for a reason you expect. The list page ran no query, because it reads the dictionary. The heading still has the “Sample” label. The workshop’s page is a 404, and the location, the local time, the new titles, and the empty message are missing. The two escaping tests fail because the old pages never show the saved titles. Chapter 18’s nine tests, and the events tests that do not depend on the data, still pass.
Common Error: DatabaseOperationForbidden
If a test fails with DatabaseOperationForbidden and a message that database queries are not allowed in SimpleTestCase, its class still inherits from SimpleTestCase but saves an event. Change the base class to TestCase, as in the listings. Only EventRowPartialTests, DesignSystemTests, and EventModelTests stay SimpleTestCase.
Step 6: Read events from the database
Replace events/views.py with this:
events/views.py
"""The events app's views: one function per page."""
from django.shortcuts import get_object_or_404, render
from .models import Event
def home(request):
"""Welcome visitors to Otahque."""
return render(request, 'events/home.html')
def event_list(request):
"""List the published events."""
events = Event.objects.filter(
status=Event.Status.PUBLISHED
)
return render(
request, 'events/list.html', {'events': events}
)
def event_detail(request, event_id):
"""Show one published event, or 404."""
event = get_object_or_404(
Event, pk=event_id, status=Event.Status.PUBLISHED
)
return render(
request, 'events/detail.html', {'event': event}
)
SAMPLE_EVENTS and the Http404 import are gone. event_list passes a QuerySet to the template without running it; the template’s {% for %} loop evaluates it, with one query, in the model’s order, soonest first. event_detail asks for the event with this id and the published status: a draft or a cancelled event matches nothing, so get_object_or_404() raises Http404, exactly as for an id that does not exist. A visitor cannot tell a hidden event from a missing one, which is what the rule intends. The address pattern from Chapter 10 accepts whole numbers only, so /events/abc/ never reaches the view.
The heading, the page title, and the empty message lose the word “sample”, the sentence about fictional events goes, and {{ event.title }} no longer passes through the sample_label filter, so the {% load event_labels %} line goes too. event.id and event.title were dictionary keys; now they are the model’s fields, and the template does not need to know the difference. Replace events/templates/events/detail.html:
{% load tz %} loads Django’s time zone tags. Inside {% timezone event.timezone %}, every datetime, the start and the end alike, is shown in the zone the event names, such as Asia/Kolkata, instead of the project’s TIME_ZONE, UTC. The date filter formats it: l is the weekday, j the day without a leading zero, F the month’s name, Y the year, H:i the 24-hour time, and T the zone’s abbreviation. The end shows its full date too, so an event that ends on another day still reads correctly. One fixed format is enough for now; Chapter 61 decides how Otahque formats dates and times for different languages and regions. The title in the title block is escaped like any other variable, which the escaping test proves.
Nothing loads event_labels any more. Delete the events/templatetags folder, which holds only the filter and an empty __init__.py. In PowerShell, beside manage.py:
PowerShell
Remove-Item -Recurse events\templatetags
In Git Bash, a macOS shell, or Linux/WSL Bash:
Terminal
rm -r events/templatetags
The filter did its job in Chapter 12, which still teaches how to write one. Code whose purpose has ended is deleted, not left behind for the next reader to wonder about; Git keeps the old version if you ever need it.
Two parts of the stylesheet source belonged to the filter. Open static/otahque/source.css. Near the top, delete the line that tells Tailwind to scan the deleted folder:
static/otahque/source.css (delete this line)
@source "../../events/templatetags";
Near the end, inside @layer components, delete the rule for the label, keeping the two .site-nav rules above it and the closing brace of the layer:
Then rebuild the stylesheet with Chapter 14’s command, in any of the four shells:
Terminal
npm run build
The build ends with Done in, then a time. site.css loses the .sample-label rule. It also loses daisyUI’s .filter rules: Tailwind adds a rule for any class name it finds in the files it scans, and the word filter in @register.filter matched a daisyUI component that Otahque never used. Removing the folder removed the match. Run every test:
Terminal
uv run python manage.py test
Expected result, shortened with ...:
Output
Found 30 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
..............................
...
Ran 30 tests in ...
OK
Destroying test database for alias 'default'...
Common Error: an old template tag library
If a page fails with TemplateSyntaxError and the message says that 'event_labels' is not a registered tag library, a template still has {% load event_labels %}. Remove the line; the listings in this step have none.
Now look at the pages. Start the development server:
Terminal
uv run python manage.py runserver
Open http://127.0.0.1:8000/events/. The heading says “Events”, and the list shows Python meetup, then Django workshop; Spring planning is not there. Select Django workshop: its page shows From Thursday 3 December 2026, 14:30 IST, Until Thursday 3 December 2026, 17:30 IST, and Virtual. Go back and select Python meetup: Thursday 19 November 2026, 18:30 GMT and Leeds Central Library, Room 2. Now type the draft’s address, http://127.0.0.1:8000/events/3/, using your draft’s id if it is not 3. The page says “Page not found (404)”, and because DEBUG is on, Django’s explanation includes No Event matches the given query. With DEBUG off, as on a real server, visitors see only a plain “Not Found” page. Stop the server with Ctrl+C.
If a draft appears on a page, one view is missing the status condition, and the failing test names which page. If the time shows 09:00 and UTC, the {% load tz %} line or the {% timezone %} block is missing from detail.html.
Step 7: Review and commit
Look at what changed:
Terminal
git status --short
Output
M events/templates/events/detail.html
M events/templates/events/list.html
D events/templatetags/__init__.py
D events/templatetags/event_labels.py
M events/tests.py
M events/views.py
M static/otahque/site.css
M static/otahque/source.css
Eight files: two templates, two deleted files, the tests, the views, and both stylesheet files. D marks a deleted file. There is no db.sqlite3, because Git ignores it, so your three events stay on your computer. If db.sqlite3 appears, .gitignore has lost Chapter 8’s line; restore it rather than committing the database. Commit:
Terminal
git add events static
git commit -m "Read published events from the database"
git add events stages the deletions as well as the changes. git status --short then prints nothing.
When something goes wrong
Table 19.3 — ORM and page problems and safe recovery
Symptom
Likely cause
Safe recovery
no such table: events_event
migrate has not run on this database
Run migrate; it applies only what is missing
name 'Event' is not defined
Plain python, or shell --no-imports
Start manage.py shell as shown
RuntimeWarning: ... received a naive datetime
tzinfo=UTC left out
Delete the row; create it again with tzinfo=UTC
TypeError: unexpected keyword, or FieldError: Cannot resolve keyword
Work through Table 19.4 from the folder that holds manage.py. The test rows come first: they are the evidence that the pages follow the published rule whatever rows the database holds.
Table 19.4 — Verification checklist for Chapter 19
Check
Command or action
Expected result
Red stage seen
The Step 5 run, before the views changed
Found 30 test(s); FAILED (failures=10)
Tests pass
uv run python manage.py test
Found 30 test(s); OK
Your events
The last loop of Step 4, in the shell
1 and 2 published, 3 draft
List page
http://127.0.0.1:8000/events/
Python meetup, then Django workshop; no Spring planning
Local time
The Django workshop's page
Thursday 3 December 2026, 14:30 IST
Draft hidden
/events/3/, or your draft's id
Page not found (404)
Filter deleted
git ls-files events
No templatetags files
Committed
git status --short
No output
Not verified
macOS, Linux, WSL; PostgreSQL
Readers on those systems; Chapter 32
The query count has no row of its own: test_published_events_soonest_first checks it every time the tests run, so a later change that adds a query per event fails at once. This chapter’s commands were checked in Windows PowerShell 5.1 and Git Bash, with the shell sessions typed into a Windows console; the last row records what was not.
Que. 2 Both filter() and get() are asked for an event titled Nope, and there is none. What does each do?
Flip to check your answerFold answer back
Answer. filter() returns an empty QuerySet, <QuerySet []>, and raises nothing. get() raises Event.DoesNotExist, because it promises exactly one object. Use filter() when “none” is a normal answer, and get(), or get_object_or_404() in a view, when exactly one must exist.
Que. 3 Raj stores the published events in a variable, events. Next he loops over events to collect the titles, and then he calls events.count(). How many queries ran, and why?
Flip to check your answerFold answer back
Answer. One. Storing the QuerySet runs nothing. The loop evaluates it: one query, and the rows are cached. count() on a fully evaluated QuerySet uses the length of its cache instead of asking the database.
Que. 4 The list view filters on status. Why must the detail view filter on status too?
Flip to check your answerFold answer back
Answer. Because a visitor can type any address. If the detail view looked events up by id alone, /events/3/ would show the draft to anyone who guessed its id, even though the list never links to it. Each page that serves visitors enforces the rule itself, and a test proves it for each.
Que. 5 In Step 4, update() on a QuerySet holding only the meetup returned 1. What does update() not do?
Flip to check your answerFold answer back
Answer. It does not call save() on any model, so code in a custom save() does not run, and it does not change the meetup object already in Python, which keeps its old status until refresh_from_db(). It does not validate the value either: update(status='archived') would be stored just as readily.
Mini-Challenge
Que. 6 Sam asks: “Which published events are in Leeds this year, soonest first?” In the shell, without changing any rows, write one QuerySet that answers him, print its titles, and predict, before running it, how many queries printing the titles runs. Then check your prediction with CaptureQueriesContext.
Flip to check your answerFold answer back
Answer. One QuerySet, three conditions, and the model’s order. Here is one session that answers it:
Django shell
>>> from django.test.utils import CaptureQueriesContext
>>> leeds = Event.objects.filter(
... status=Event.Status.PUBLISHED,
... location__icontains='leeds',
... starts_at__year=2026,
... )
>>> with CaptureQueriesContext(connection) as queries:
... print([event.title for event in leeds])
...
['Python meetup']
>>> len(queries)
1
Several keyword arguments in one filter() must all be true, which SQL writes with AND. icontains matches Leeds Central Library, Room 2, where an exact location='Leeds' would not. No order_by() is needed, because the model’s ordering is soonest first. Building the QuerySet runs nothing, and the list comprehension runs exactly one query. Your answer may differ, for example with location__startswith='Leeds', and still be right if it returns the meetup alone.
What We Learned
The ORM translates between model objects and rows: it writes the SQL, sends values as parameters, and builds an object per row.
Event.objects is the model’s manager; all(), filter(), exclude(), and order_by() return QuerySets, each a new one.
get() returns exactly one object or raises DoesNotExist or MultipleObjectsReturned; filter() returns a QuerySet that may be empty.
Field lookups use two underscores, such as title__icontains and starts_at__gte; several conditions in one filter() must all match.
A QuerySet runs its query when evaluated, caches the rows, and reuses them; a new QuerySet queries again. CaptureQueriesContext and assertNumQueries count queries.
save(), save(update_fields=...), update(), and delete() change rows; none of them validates the values.
Public pages filter on the published status in every view, with get_object_or_404() for the detail page, and a test proves the rule for each page.
{% timezone %} shows a stored UTC time in the event’s own zone.
Code that no longer has a purpose, such as the sample filter, is deleted.
Key terms
Use Table 19.5 to explain this chapter’s ideas in your own words.
Table 19.5 — Key terms from Chapter 19
Term
Meaning
ORM
Object-relational mapper: turns Python queries into SQL and rows into objects.
Manager
The object on a model, such as Event.objects, through which queries start.
QuerySet
A description of a query that runs when it is evaluated, then caches its rows.
Field lookup
A condition such as title__icontains: field, two underscores, and lookup.
Evaluation
The moment a QuerySet runs its query, such as when a loop starts.
Result cache
The objects a QuerySet keeps after its query has run.
Primary key
The column that identifies each row; pk on a Django model.
Aware datetime
A datetime that knows its time zone, such as one with tzinfo=UTC.
SQL injection
Changing a query's meaning by placing SQL inside a value.
Query parameter
A value sent beside the SQL text, never as part of it.
setUpTestData
A TestCase class method that creates rows once for every test in the class.
Readiness checkpoint: you are ready for Chapter 20 when all 30 tests pass, the last loop of Step 4 shows two published events and one draft, /events/ lists only the published events soonest first, the workshop’s page shows 14:30 IST, the draft’s address returns 404, and git status --short prints nothing. Explain, in a sentence, why test_published_events_soonest_first would fail if someone later changed the list page to run a separate query for each event. Return to the relevant step if any result is missing.
Git Commit
Your Chapter 19 work was committed in Step 7. For the record, these were the commands, in any of the four shells, beside manage.py:
Terminal
git add events static
git status --short
Output
M events/templates/events/detail.html
M events/templates/events/list.html
D events/templatetags/__init__.py
D events/templatetags/event_labels.py
M events/tests.py
M events/views.py
M static/otahque/site.css
M static/otahque/source.css
Terminal
git commit -m "Read published events from the database"
The letters moved to the first column because the changes are now staged. Your three events are not in the commit: rows live in db.sqlite3, and Chapter 41 chooses how Otahque shares sample data between computers.
These five questions rehearse the chapter at interview level, one at each of five levels from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead to a larger application with a team: attempt them now, and return to them after Chapters 22 and 57. They are extension questions, not a gate to the next chapter. Each code proof except L5’s is a short file in the practice folder that starts by importing Chapter 16’s setup_django.py; run it from the folder that holds manage.py with uv run python ../practice/ followed by the file name. The proofs read your three events and leave them as they are.
L1 (Junior): What is the difference between get() and filter(), and what does each do when nothing matches?
What the interviewer is testing: Do you know which method promises one object, and how to handle the cases where that promise fails?
Flip to check your answerFold answer back
Perfect answer:get() returns exactly one model object. When no row matches, it raises the model’s DoesNotExist error; when more than one matches, it raises MultipleObjectsReturned. I use it when exactly one row must exist, usually by primary key or another unique field, and I catch the named error rather than a bare Exception. In a view, I use get_object_or_404(), which turns a missing row into a 404 page. filter() returns a QuerySet of every match, which may be empty, and raises neither error; it is also lazy, so it does not run until it is evaluated. I use it for lists, and with first() when I want one object or None.
Table 19.6 — get() and filter() compared
Question
get()
filter()
Returns
One model object
A QuerySet
Nothing matches
Raises DoesNotExist
An empty QuerySet
Several match
Raises MultipleObjectsReturned
All of them
Runs the query
At once
When evaluated
Typical use
One row by a unique field
Lists and searches
Behind the scenes:
get and filter (summary)
get(pk=1) -> one object, now, or an exception
filter(...) -> a QuerySet, later, maybe empty
filter().first() -> one object or None
view -> get_object_or_404() for a 404 page
Code proof: both methods, asked for a title no event has:
../practice/l1_get_filter.py
import setup_django
from events.models import Event
print(Event.objects.filter(title='Nope'))
try:
Event.objects.get(title='Nope')
except Event.DoesNotExist as error:
print('get():', error)
print(Event.objects.filter(title='Nope').first())
Output
<QuerySet []>
get(): Event matching query does not exist.
None
Common mistakes:
Using get() on a field that is not unique, so it fails once a second matching row appears.
Expecting filter() to return one object, then reading .title on the QuerySet.
Wrapping get() in except Exception, which also hides typos in field names.
Follow-up the interviewer might ask:
“How would you fetch one event by id in a view, and what should a visitor see if it is hidden?”
“When is filter(...).first() better than get()?”
L2 (Mid-Level): When does a QuerySet hit the database, and when does it reuse results?
What the interviewer is testing: Can you predict queries from code, which is the basis of every performance conversation about the ORM?
Flip to check your answerFold answer back
Figure 19.3 — When a QuerySet runs, and when it reuses its rows.
Perfect answer: Building and chaining a QuerySet never queries the database: filter(), exclude(), and order_by() return new, unevaluated QuerySets. The query runs when the QuerySet is evaluated: iterating over it, including in a template, calling list(), len(), or bool(), printing it, or slicing it with a step. Evaluation fills the QuerySet’s result cache, and iterating the same QuerySet again, or calling count() or exists() on it once fully evaluated, uses that cache. A new QuerySet, even from identical code, has an empty cache, so Event.objects.count() written twice runs two queries. Slicing or indexing an unevaluated QuerySet runs a limited query each time and does not fill the cache. So I keep one QuerySet in a variable when I need its rows more than once, I use count() or exists() on an unevaluated QuerySet when I need only a number or a yes, and I check the count in tests with assertNumQueries.
Behind the scenes:
laziness (summary)
filter(), order_by() -> new QuerySet, 0 queries
for, list(), len(), bool -> 1 query, rows cached
same QuerySet again -> cache, 0 queries
new QuerySet, same code -> 1 more query
Code proof: one QuerySet used twice, then a new one built from the same code:
../practice/l2_laziness.py
import setup_django
from django.db import connection
from django.test.utils import CaptureQueriesContext
from events.models import Event
with CaptureQueriesContext(connection) as queries:
published = Event.objects.filter(status='published')
print('built:', len(queries))
first_pass = list(published)
second_pass = list(published)
print('same QuerySet twice:', len(queries))
again = list(Event.objects.filter(status='published'))
print('new QuerySet:', len(queries))
Output
built: 0
same QuerySet twice: 1
new QuerySet: 2
Common mistakes:
Building a new QuerySet inside a loop, so each pass queries again.
Calling len() on a QuerySet only to count it, which loads every row; count() asks for a number.
Assuming that [0] on an unevaluated QuerySet uses a cache.
Follow-up the interviewer might ask:
“Why does if events: run a query, and when is exists() better?”
“How would you prove in a test that a page’s query count does not grow with its data?”
L3 (Senior): What do save(), save(update_fields=...), and QuerySet update() each send, and what does none of them do?
What the interviewer is testing: Do you know exactly what reaches the database when a row changes, and where validation actually happens?
Flip to check your answerFold answer back
Figure 19.4 — Three ways to write a change, and what none of them checks.
Perfect answer:save() on an existing object sends one UPDATE that sets every column from the object’s attributes, so it can overwrite a change another process made to a column this code never touched. save(update_fields=[...]) sends an UPDATE of only the named columns, which avoids that and sends less. Both go through the model’s save() method and its signals. QuerySet update() sends one UPDATE ... WHERE for every matching row; it does not call save(), does not send the pre_save or post_save signals, does not change objects already loaded in Python, and returns the number of rows matched. None of the three calls full_clean(): Django’s model validation runs only when called, as forms do. So data rules belong in two places: validation in forms and other entry points, for helpful messages, and database constraints, which refuse bad data whichever code path writes it. In Otahque, Chapter 21 adds those constraints and Chapter 24 the forms.
Behind the scenes:
writes (summary)
obj.save() -> UPDATE every column
obj.save(update_fields=x) -> UPDATE only x
qs.update(f=v) -> one UPDATE, no save()
none of them -> full_clean()
Code proof: how many columns each write sets, captured inside a transaction that is rolled back, so your events stay as they are:
../practice/l3_writes.py
import re
import setup_django
from django.db import connection, transaction
from django.test.utils import CaptureQueriesContext
from events.models import Event
def columns(queries):
sql = queries[-1]['sql']
return re.findall(r'SET (.*) WHERE', sql)[0].count('=')
with transaction.atomic():
event = Event.objects.get(title='Python meetup')
with CaptureQueriesContext(connection) as q:
event.save()
print('save():', columns(q), 'columns')
with CaptureQueriesContext(connection) as q:
event.save(update_fields=['location'])
print('update_fields:', columns(q), 'column')
rows = Event.objects.filter(pk=event.pk)
print('update():', rows.update(status='archived'))
print('stored:', rows.get().status)
transaction.set_rollback(True)
event.refresh_from_db()
print('after rollback:', event.status)
Output
save(): 7 columns
update_fields: 1 column
update(): 1
stored: archived
after rollback: published
save() set all seven columns besides the id; update_fields set one. update() stored a status that is not one of the choices, without complaint. transaction.atomic() groups the writes, and set_rollback(True) undoes them all at the end of the block; refresh_from_db() then reads the row as the database holds it again.
Common mistakes:
Believing the model’s choices or required fields stop bad values on save().
Putting important logic in save() and then using update(), which skips it.
Reading an object after update() without refresh_from_db().
Follow-up the interviewer might ask:
“Two people edit different fields of the same event at once. What can go wrong with save()?”
“Where would you enforce that capacity is at least one?”
L4 (Staff): After organizer names were added to the events page, it went from 1 query to 41. How do you find and fix it?
What the interviewer is testing: Looking ahead: can you recognize a query per row, measure it, and fix it without guessing?
Flip to check your answerFold answer back
Figure 19.5 — Finding and fixing a query per row.
Perfect answer: Forty-one queries for forty events is the classic pattern called N+1: one query for the list, then one more for each row, because the template reads event.organizer.display_name and each access loads that related row on its own. I would confirm it first, with assertNumQueries in a test, CaptureQueriesContext, or a tool such as Django Debug Toolbar, and look at the repeated query. For a foreign key, select_related('organizer') fetches the organizer in the same query with a join; for many-to-many or reverse relations, prefetch_related() fetches them in one extra query. Then I would keep the list page’s test asserting a fixed number of queries with several events, so the problem cannot return quietly. Otahque has no relationships yet: Chapter 20 adds them, Chapter 22 composes such queries, and Chapter 57 measures them.
Behind the scenes:
N+1 (summary)
1 query -> the list of events
+1 per event -> event.organizer, loaded on access
select_related -> one query with a JOIN
test -> assertNumQueries(1) with many rows
Code proof: relationships arrive in Chapter 20, so this proof shows the same shape with what exists now: a query written inside a loop, against the same answer worked out from one query:
../practice/l4_per_row.py
from collections import Counter
import setup_django
from django.db import connection
from django.test.utils import CaptureQueriesContext
from events.models import Event
with CaptureQueriesContext(connection) as q:
for event in Event.objects.all():
Event.objects.filter(location=event.location).count()
print('query per row:', len(q))
with CaptureQueriesContext(connection) as q:
events = list(Event.objects.all())
Counter(event.location for event in events)
print('one query:', len(q))
Output
query per row: 4
one query: 1
With three events, the loop ran 1 + 3 queries; with forty, it would run 41. The second version runs one, however many events there are.
Common mistakes:
Adding caching before measuring, which hides the queries instead of removing them.
Using prefetch_related() for a foreign key, where select_related() needs no extra query.
Testing the query count with one event only, where N+1 cannot show.
Follow-up the interviewer might ask:
“When is a second query from prefetch_related() better than a join?”
“How would you stop a template from triggering queries at all?”
L5 (Lead): How would you stop drafts leaking onto public pages as the number of views grows?
What the interviewer is testing: Looking ahead: can you turn a rule that lives in one query into a rule that holds across a team and a growing codebase?
Flip to check your answerFold answer back
Figure 19.6 — Keeping a visibility rule true as a codebase grows.
Perfect answer: Today the rule is written twice, as a filter() in the list view and a condition in the detail view. That works for two pages, but each new public page, feed, sitemap, or search result is a new chance to forget it. I would make the rule explicit and hard to miss. First, write it down as a product rule: visitors see published events only. Second, give it one home in code, a named QuerySet method such as Event.objects.published(), which Chapter 22 adds, so that views ask for published events instead of repeating the condition. Third, test it per page: every public page gets a test that saves a draft and a cancelled event and proves they are absent or return 404, as this chapter’s tests do. Fourth, review public views for bare Event.objects queries, and make the safe method the easy default. Finally, run the tests on every change before it is merged, which Chapter 34 automates. I would not hide drafts in templates, because a template can only hide what the query already loaded.
Behind the scenes:
visibility rule (summary)
rule -> written down: published only
code -> one method: Event.objects.published()
tests -> each public page: draft and cancelled hidden
process -> review, then tests before every merge
Code proof: the detail page’s tests, including the one that saves a draft and a cancelled event and expects 404 for both, after checking the published page. In PowerShell:
PowerShell
uv run python manage.py test -v 2 `
events.tests.EventDetailTests
In Git Bash, a macOS shell, or Linux/WSL Bash:
Terminal
uv run python manage.py test -v 2 \
events.tests.EventDetailTests
Expected result, shortened with ...:
Output
Found 5 test(s).
...
test_invalid_id (events.tests.EventDetailTests.test_inval...
test_missing_event (events.tests.EventDetailTests.test_mi...
test_published_event (events.tests.EventDetailTests.test_...
test_time_in_event_time_zone (events.tests.EventDetailTes...
test_unpublished_events_are_hidden (events.tests.EventDet...
...
Ran 5 tests in ...
OK
...
-v 2 names each test as it runs, and on your screen each line ends ok. The last test is the rule’s guard on this page; Chapter 22 keeps every such test when the condition moves into published().
Common mistakes:
Hiding drafts with {% if %} in a template, after the query has loaded them.
Testing the list page and assuming the detail page follows.
Adding a new public page without a visibility test.
Follow-up the interviewer might ask:
“Should a cancelled event’s page return 404, or show a notice? Who decides?”
“How would you make the unsafe query harder to write than the safe one?”
Next: Chapter 20 connects tables, with the relationships that let a member register for an event.