Chapter 22 · QuerySets, managers, and query composition: named questions about Otahque’s dataCHAPTER 22
Complete six-part pre-release for review. The list page shows upcoming events first, with places left, and past events after them, faded; the detail page shows places left; no migration is added; the admin site arrives in Chapter 23.
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 TWENTY-TWO
QuerySets, managers, and query composition: named questions about Otahque’s data
Stage 3: Data and the database (Chapters 15 to 23)
Prerequisites: Chapters 15 to 21, including the Chapter 21 project, its 51 passing tests, its four events, three members, and their registrations
What you’ll build: A custom QuerySet for events with a published() method that both public views use, upcoming() and past() methods that put past events last on the list, faded, and with_places(), which shows how many places are left, a custom QuerySet for registrations with an active() method, and single-query answers to Otahque’s audit questions with Q, F, annotate(), and Prefetch, proved by tests written first.
Why This Matters
Chapter 19 ended with a rule written twice. The event list asks for events whose status is published, and the detail page asks the same question in its own words. Both are right today. The risk is the third page: a calendar feed, a search result, or a sitemap, written months later by someone who never read Chapter 19, which forgets the condition and shows Sam’s draft to every visitor. Chapter 19 promised to give the rule one home, a named method called published(), once you had seen the repetition it removes.
Other questions have collected since then. Chapter 16 said a single query can choose its own order. Chapter 20 loaded related rows with select_related() and asked where that belongs once queries have names. Chapter 21 used Q and F in constraints and left audit questions that need more: do the rows already obey its time rules, how many active places does each event hold, and is any event holding more than its capacity? Each of these is one query, if you know how to compose it.
The event list has a problem of its own. Chapter 16 sorted events soonest first, so as dates pass, events that have already ended collect at the top of the list, above the ones a visitor could still attend. Sam has decided what the list should do: events that are happening now or are still to come go first, soonest first, and events that have ended stay on the page below them, the most recent first, faded so that nobody mistakes them for something to join. “Has it ended?” is another question every visit asks, and it deserves a name too. Sam also wants visitors to see how many places are left on each event that is still to come, which is a count, and the next questions show how to make the database do the counting.
By the end of the chapter, you will be able to:
explain the difference between a manager and a QuerySet, and why a method that selects rows belongs on a QuerySet;
write a custom QuerySet, attach it with as_manager(), and move a repeated rule into it without changing a page;
split published events into upcoming and past with methods that take the current time, and show past events last;
combine conditions with Q and the operators &, |, and ~, and compare two fields of a row with F;
choose an order with order_by(), and count with annotate(), aggregate(), and Count(filter=...);
show a count on a page without a query per row, by annotating it in the query the page already runs;
load related rows for a named query with Prefetch, and read the SQL that a QuerySet sends.
The detail page does not change in this chapter. The list page changes on purpose in Step 6, where past events move below the others and are faded, and both pages show places left from Step 8. The admin site is Chapter 23, the pages where members see their own registrations are Chapter 31, pagination is Chapter 36, and query tuning is Chapters 55 to 57.
Two facts from Chapter 19 carry this chapter. A QuerySet is lazy: building one, or adding filter() to it, sends nothing to the database, and the query runs only when something needs the rows, such as a loop, list(), or a template. And every QuerySet method that refines a query, such as filter(), exclude(), or order_by(), returns a new QuerySet and leaves the old one unchanged. If either is unfamiliar, reread Chapter 19’s “When a query runs” before going on: everything below depends on them.
Managers and QuerySets, again
Chapter 19 called Event.objects the model’s manager: the object that starts every query. Chapter 17 wrote a manager of its own, UserManager, and Chapter 21 extended it. Its methods, create_user() and create_superuser(), create rows. This chapter adds methods that select rows, and those need a different home.
A manager’s methods exist only on the manager. User.objects.create_user() works, but User.objects.filter(is_staff=True).create_user() fails, because filter() returns a QuerySet, and create_user() is not a QuerySet method. For creating rows that does not matter: you never create a user from the middle of a query. For selecting rows it matters a great deal. You want Event.objects.published(), and also Event.objects.filter(location='Virtual').published(), and Event.objects.published().order_by('-starts_at'), all to work.
New Concept: a custom QuerySet
What problem exists? A rule such as “visitors see published events” is a condition that many queries need, in different combinations with other conditions.
What did people do before? They wrote the condition in each view, as Chapter 19 did, or added a method to a custom manager, which works only at the start of a query.
What is it? A custom QuerySet is a subclass of models.QuerySet whose methods return refined QuerySets, such as return self.filter(status=...). Because every QuerySet method returns a QuerySet of the same class, these methods can be called anywhere in a chain. EventQuerySet.as_manager() builds a manager with a copy of the same methods, so the chain can also start with them.
Why use it? The rule gets one name and one home, beside the model it describes, and every query that needs it says so in words: Event.objects.published().
Now let’s use it. Step 4 writes EventQuerySet, Step 6 uses two more of its methods on the list page, and Step 7 writes RegistrationQuerySet.
Table 22.1 sets the two kinds of method side by side.
Table 22.1 — Manager methods and QuerySet methods
Kind
Otahque example
Can follow filter()?
Manager method
User.objects.create_user()
No
QuerySet method
Event.objects.published()
Yes
Built-in QuerySet method
filter(), exclude(), order_by()
Yes
The chain in Figure 22.1 runs from the manager to the SQL it sends, with a manager method beside it for contrast.
Figure 22.1 — Each QuerySet method returns a new QuerySet; the chain becomes one SQL statement when it runs.
Under the Hood: what as_manager() builds
as_manager() creates a new Manager subclass at the moment the model class is defined, named after the QuerySet, such as ManagerFromEventQuerySet, and copies the QuerySet’s public methods onto it. Each copied method simply calls get_queryset(), which returns a fresh EventQuerySet, and then calls the method on it. Methods whose names start with an underscore are not copied, and neither is delete(), so that Event.objects.delete() cannot empty a table by accident. Two more consequences matter in this chapter. A reverse relationship’s manager, such as meetup.registrations from Chapter 20, is built as a subclass of the related model’s default manager class, so a method on RegistrationQuerySet also works on meetup.registrations. And a manager is stored in a migration only when it sets use_in_migrations = True, as Chapter 17’s UserManager does so that data migrations can create users. These QuerySet managers do not, so this chapter writes no migration.
Manager.from_queryset() is the third shape. It builds a manager from a manager class of your own and a QuerySet class, for the rare model that needs both: methods that create rows and methods that select them. Otahque’s UserManager could become one if members ever need named queries; nothing needs that yet.
Combining conditions: Q and F
Keyword arguments to filter() are joined by “and”: filter(status='draft', capacity__lt=20) means both. Chapter 21 wrote one condition as a Q object and joined two with |. A Q object is a condition kept as a value, so it can be named, stored in a variable, and combined:
a | b holds when either holds (“or”);
a & b holds when both hold (“and”);
~a holds when a does not (“not”).
Q objects go into filter(), exclude(), and get() as positional arguments, before any keyword arguments.
The second tool compares a field with another field of the same row. Chapter 21 used it once, inside the constraint that an event ends after it starts; here it goes into queries. filter(cancelled_at__lt=...) needs a value on the right, but “cancelled before it was made” compares two columns. An F expression, F('registered_at'), refers to a field’s value in the database, row by row. filter(cancelled_at__lt=F('registered_at')) becomes WHERE cancelled_at < registered_at. F also works in arithmetic, such as F('capacity') + 10, and in update(), where the database computes the new value itself.
New Concept: Q and F expressions
What problem exists? Some questions need “or” and “not”, and some compare one column with another, which keyword arguments alone cannot say.
What did people do before? They loaded rows into Python and tested each one, or wrote SQL by hand.
What are they?Q(...) is a condition object, combined with &, |, and ~. F('field') is a reference to a column, used where a value would go. Both become part of the SQL, so the database does the work.
Why use them? One query answers the question, however many rows there are, and the condition can be given a name and reused.
Now let’s use it. Step 9 asks Otahque’s audit questions with both.
One case needs care: a column that can be empty. In SQL, a comparison with NULL, the database’s “no value”, is neither true nor false, so cancelled_at < registered_at is not true for an active registration, whose cancelled_at is empty. filter() keeps only rows where the condition is true, so it skips them. exclude() keeps the rows where it is not true, so it includes them. Step 9 shows the difference with real rows.
Choosing an order
Chapter 16 gave Event the option ordering = ['starts_at'], so every event query is soonest first unless it says otherwise. order_by('-starts_at') says otherwise: the minus sign reverses the order, and each order_by() call replaces any earlier order, including the model’s. order_by() with no arguments removes ordering altogether, which saves the database a sort when order does not matter. A QuerySet’s ordered attribute tells you whether it has an order at all.
Upcoming and past: asking about now
Whether an event is upcoming or past depends on one more value: the current time. django.utils.timezone.now() returns it as an aware datetime in UTC, the same form as starts_at and ends_at, so comparing them is correct whatever zone an event is in: the Kolkata workshop and the Leeds meetup are compared as instants, and each page still shows its own local time. An event is past once its end time has gone by. An event that has started but not ended is still worth showing at the top, because people can still join it, so “upcoming” means “not yet ended”: ends_at__gt=now.
A method that called now() itself would be hard to test, because its answer changes with the clock: a test written in November would fail in December. So Otahque’s methods take now as an argument. Tests pass a fixed instant, and the list view calls timezone.now() once and passes the same instant to both methods, so no event can fall between the two lists while the page is being built.
Counting: annotate() and aggregate()
Chapter 21 found duplicate registrations by fetching pairs into Python and counting them with Counter. The database can count for you.
New Tool: annotate(), aggregate(), and Count
What problem exists? Questions such as “how many active places does each event hold?” need a number per row, or one number for a whole set of rows.
What did people do before? They looped over rows in Python, which fetches every row and runs a query per event to count its registrations.
What are they?Count('registrations') is an aggregate: a value computed from many rows. annotate(places=Count(...)) adds it to each object in the result, as event.places, and returns a QuerySet you can keep refining. aggregate(total=Count(...)) computes it over the whole QuerySet and returns a dictionary; it ends the chain. Count(..., filter=Q(...)) counts only the related rows that match. alias() is annotate() without returning the value, for a number you only filter on.
Why use them? The database counts in one query, with a join and grouping, whatever the number of events.
Now let’s use it. Step 8 puts the count of places left on both event pages, and Step 10 counts in the shell and redoes Chapter 21’s duplicate check.
One annotated query counts each event’s active places, as Figure 22.2 shows.
Figure 22.2 — annotate() joins each event to its registrations, groups the rows by event, and counts only the active ones.
Under the Hood: the SQL behind annotate()
Event.objects.annotate(places=Count('registrations', filter=...)) becomes one statement: SELECT the event’s columns and COUNT("registrations_registration"."id") FILTER (WHERE ... = 'active'), FROM "events_event" LEFT OUTER JOIN "registrations_registration", then GROUP BY the event’s columns. The LEFT OUTER JOIN keeps events with no registrations, which count 0. FILTER (WHERE ...) is how SQLite and PostgreSQL count only matching rows; on databases without it, Django writes a CASE expression instead. Grouping has a side effect that surprises people: Django does not apply the model’s Meta.ordering to a query with GROUP BY, so the result comes back in whatever order the database chooses, and ordered is False. Add order_by() whenever the order matters. A second surprise comes from joining two relations in one query, such as registrations and organizer assignments: each event’s row is repeated once for every combination, and both counts grow. The L3 interview question works through it.
Related rows inside named queries
Chapter 20 fixed a query per row with select_related(), which joins a forward relation into the same query, and named prefetch_related(), which fetches a reverse relation in one extra query. Both are QuerySet methods, so they chain with named methods: Registration.objects.active().select_related('member') is the active places, each with its member already loaded.
A Prefetch object goes one step further: it tells prefetch_related() which QuerySet to use for the related rows, and where to put them. Prefetch('registrations', queryset=Registration.objects.active(), to_attr='active_places') loads each event’s active registrations, and only those, into a list called event.active_places. The named method appears inside the prefetch, so the rule “active” still has one home.
Try it yourself
Que. 1 Chapter 19’s list view runs one query. If the view asked for Event.objects.published().filter(location='Virtual'), how many queries would it run, and why does that matter for named methods?
Flip to check your answerFold answer back
Answer. Still one. published() and filter() each return a new QuerySet, and nothing runs until the template loops over the result, so both conditions are joined into one WHERE clause. Named methods cost nothing extra: they only build the query.
Prefer a QuerySet method, a manager method, or a helper function?
A method that selects rows belongs on a custom QuerySet, attached with as_manager(), so it works at any point in a chain and on related managers. A method that creates rows, or does something before a query exists, belongs on a manager, as create_user() does. A plain function such as published_events() in views.py works for one view, but it cannot follow filter(), related managers do not have it, and the next view’s author has to know it exists. Give a rule a method only when real code repeats it: a QuerySet with thirty one-line methods is as hard to read as the views it replaced.
Two cautions go with that advice. Name methods after the question, not the SQL: published(), not status_equals_published(). And keep the default manager, objects, unfiltered. The L4 interview question explains what goes wrong when it hides rows.
In practice: a weekly count for organizers
Situation. Sam wants to know, each Monday, how many active places each of his events holds, to plan rooms and refreshments.
Application. One annotated query answers it: Event.objects.annotate(places=Count('registrations', filter=Q(registrations__status='active'))), filtered to his events and ordered by start time. It runs as one query whether Sam organizes three events or three hundred.
Consideration. The number is a snapshot, true when the query ran. It does not stop the next registration from going over capacity: that needs a transaction and a lock, in Chapter 33. Visitors see the same kind of snapshot from Step 8: the places left when the page was built. Organizers such as Sam will see counts on Otahque’s own organizer pages, which later chapters build; the admin site is the administrator’s tool, not an organizer page.
Start from Chapter 21, in the folder containing manage.py, with your own .env, the locked environment, 51 passing tests, every migration applied, and the rows from Chapter 21: four events, two of them published; Sam, Sai, and Raj; Sai’s two active registrations and Raj’s cancelled one; and Sam’s organizer assignment. Step 2 finds the repeated rule. Step 3 writes four tests first. Step 4 adds EventQuerySet to events/models.py, and Step 5 changes both views in events/views.py without changing what they show. Step 6 then changes the list page on purpose, in events/views.py, events/templates/events/list.html, and the stylesheet, Step 7 adds RegistrationQuerySet to registrations/models.py, and Step 8 shows the places left on both pages, with a new template, events/templates/events/places.html. Steps 9 and 10 ask Otahque’s audit questions in the shell, and Step 11 commits. At the end, 58 tests pass, the list page shows past events last and faded, both pages show the places left on events still to come, and there is no new migration.
The Custom Way
Without a query layer, composition is done in Python. This illustration filters a list of dictionaries with two functions; run it with any Python, and do not add it to the project:
illustration_only/by_hand.py (not part of the project)
events = [
{'title': 'Python meetup', 'status': 'published',
'location': 'Leeds Central Library, Room 2'},
{'title': 'Django workshop', 'status': 'published',
'location': 'Virtual'},
{'title': 'Spring planning', 'status': 'draft',
'location': 'Leeds Central Library'},
]
def published(rows):
return [row for row in rows
if row['status'] == 'published']
def in_person(rows):
return [row for row in rows
if row['location'] != 'Virtual']
chosen = in_person(published(events))
print([row['title'] for row in chosen])
Output
['Python meetup']
It works, and the two rules have names. Now list what it costs. Every row is already in Python’s memory: with a database, published() would first fetch every event ever stored, then throw most of them away. Each function runs at once and builds a new list, so the work is repeated for every rule. The calls nest inside out, in_person(published(events)), so a third rule makes the line harder to read. And nothing connects the rules to the Event model. A custom QuerySet keeps the names but sends all the conditions to the database in one statement. Functions that return finished lists are also the shape of a repository layer, which the L5 interview question weighs.
The Django Way
Eleven steps follow. Step 1 checks the start, Step 2 finds the repetition, Step 3 writes the tests, Steps 4 to 8 add the two QuerySets, use one in the views, split the list page, and show places left, Steps 9 and 10 compose queries in the shell, and Step 11 commits.
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 51 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...................................................
...
Ran 51 tests in ...
OK
Destroying test database for alias 'default'...
Then start the shell, in any of the four shells, with uv run python manage.py shell, and look at the rows and at the manager:
Django shell
15 objects imported automatically (use -v 2 for details).
Python 3.14.9 ...
Type "help", "copyright", "credits" or "license" for ...
(InteractiveConsole)
>>> Event.objects.count(), User.objects.count()
(4, 3)
>>> Registration.objects.filter(status='active').count()
2
>>> type(Event.objects)
<class 'django.db.models.manager.Manager'>
>>> exit()
now exiting InteractiveConsole...
Four events, three members, and two active registrations, as Chapter 21 left them. Event.objects is Django’s plain Manager, which Django adds to every model that does not define one. If your numbers differ, rows are left from experiments of your own; keep them. The query results in Steps 9 and 10 then differ from the book’s, but each step says what the query means, so you can check your own answer.
Step 2: Find the repeated rule
Search the views for the published condition. git grep searches the files Git tracks, and works the same in every shell:
-n adds each line’s number, and -o prints only the matching text instead of the whole line. Line 12 is the list view’s filter(), and line 21 is the detail view’s call to get_object_or_404(). The same rule, written twice, in two forms: one as a keyword argument to filter(), one as a keyword argument to a shortcut. Figure 22.3 shows the change this chapter makes.
Figure 22.3 — Both public views ask one named method instead of repeating the condition.
Step 3: Write the tests first
The tests describe the new methods before they exist. Chapter 19’s page tests stay as they are for now: they already prove that drafts and cancelled events are hidden, and after Step 5 they prove that moving the rule changed nothing. Step 6 changes the list page on purpose, and changes its test first. Add a class at the end of events/tests.py, after EventRuleTests:
assertQuerySetEqual() runs the query and compares the rows, in order, with the list; transform=str turns each event into its title first. The first test also checks the order: the Python meetup, on 19 November, comes before the Django workshop, on 3 December, because published() keeps the model’s ordering. The second test is the reason for a QuerySet rather than a manager: published() must work after filter(), and exclude() must work after published(). The third fixes the clock twice. At 19:00 on 19 November the meetup, which runs from 18:30 to 20:30, has started but not ended, so it is still upcoming, before the workshop. On 25 November it has ended, so it moves to the past list. save_event() gives each event an end two hours after its start. Notice what none of the chapter’s tests check: which method a view calls. They check what a method returns, what a page shows, and how many queries it costs, so code can move between view, model, and QuerySet without a test changing, which is how Step 5 will prove it changed nothing.
Then add one method at the end of registrations/tests.py, indented inside RegistrationTests, so that it shares the class’s event, member, and active registration:
It cancels the member’s place, registers again, and expects active() to return only the new row, both from the event’s reverse manager, self.event.registrations, and from Registration.objects. Run every test:
Terminal
uv run python manage.py test
Expected result, shortened with ...:
Output
Found 55 test(s).
...
ERROR: test_published_chains_with_other_methods (events.t...
...
AttributeError: 'Manager' object has no attribute 'published'
...
ERROR: test_active_skips_cancelled_places (registrations...
...
AttributeError: 'RelatedManager' object has no attribute ...
...
FAILED (errors=4)
Destroying test database for alias 'default'...
Four new tests, four errors, each for the reason it should: none of the methods exists yet. The registration error ends 'active'. RelatedManager is the class of self.event.registrations, the reverse manager from Chapter 20.
Step 4: Give Event a QuerySet
Open events/models.py. Add a class after validate_timezone_name() and before class Event(models.Model):, separated from both by two blank lines:
events/models.py (1 of 2: before the Event class)
class EventQuerySet(models.QuerySet):
"""Named questions about events."""
def published(self):
"""Events that visitors may see."""
return self.filter(status=Event.Status.PUBLISHED)
def upcoming(self, now):
"""Events not yet ended at now, soonest first."""
return self.filter(ends_at__gt=now).order_by(
'starts_at'
)
def past(self, now):
"""Events ended by now, the latest first."""
return self.filter(ends_at__lte=now).order_by(
'-ends_at'
)
self is the QuerySet the method is called on, whatever conditions it already has, so self.filter() adds the rule to them. upcoming() and past() each add a condition on the end time and choose their own order, which replaces the model’s: soonest start first for what is to come, latest end first for what is over. Neither checks the status, so the page asks for published().upcoming(now): two rules, two names, one query. The method refers to Event, which is defined further down the file; that works, because the name is looked up only when the method runs. Then, inside Event, add one line after the status field, before class Meta::
Only the last line is new; the first two show where it goes. Naming the manager objects replaces Django’s plain manager with one built from EventQuerySet, so every existing Event.objects call keeps working and gains published().
Common Error: the class is defined after the model
If EventQuerySet comes after class Event, the project stops with NameError: name 'EventQuerySet' is not defined. The line objects = EventQuerySet.as_manager() runs while Python builds the Event class, so the QuerySet must already exist. Move the class above Event.
Run the event tests by name:
Terminal
uv run python manage.py test events.tests.EventQuerySetTests
Expected result, shortened with ...:
Output
Found 3 test(s).
...
OK
Destroying test database for alias 'default'...
Common Error: the method is on a manager
A method written on a models.Manager subclass, the shape of Chapter 17’s UserManager, passes the first test but fails the second with AttributeError: 'QuerySet' object has no attribute 'published'. filter() returns a plain QuerySet, which has no such method. Write the method on a models.QuerySet subclass and attach it with as_manager(), as above.
Step 5: Ask the views for published events
Open events/views.py and change the two views, so the whole file reads:
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 published events: upcoming, then past."""
events = Event.objects.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.objects.published(), pk=event_id
)
return render(
request, 'events/detail.html', {'event': event}
)
The list view asks for published events, and the template’s loop runs the query, as before. get_object_or_404() accepts a QuerySet as well as a model, and calls get() on it, so the detail view finds the event among published events only: a draft’s address still raises Http404. Run the event app’s tests, which include every page test from Chapter 19:
Terminal
uv run python manage.py test events
Expected result, shortened with ...:
Output
Found 33 test(s).
...
Ran 33 tests in ...
OK
Destroying test database for alias 'default'...
test_published_events_soonest_first still passes inside assertNumQueries(1), and test_unpublished_events_are_hidden still gets a 404 for a draft and a cancelled event: the behaviour and the query count are unchanged. That is what makes this a refactor, a change to how code is written that leaves what it does the same, and the tests are how you know.
Common Error: a method instead of a QuerySet
Leaving out the parentheses, get_object_or_404(Event.objects.published, pk=event_id), fails on the detail page with ValueError: First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'method'. Without (), Python passes the method itself instead of calling it. Write Event.objects.published().
Step 6: Show past events last, and faded
Step 5 changed how the views ask; this step changes what the list shows, which Chapter 19’s list test describes differently, so that test changes first. Its dates were fixed, 19 November and 3 December 2026, and once those days pass, both events would be past and the page’s order would change under the test. The new test builds its dates from the current time instead. At the top of events/tests.py, add one import after the django.urls line:
events/tests.py (one new import)
from django.utils import timezone
Then replace the whole EventListTests class with this:
events/tests.py (EventListTests, replaced)
class EventListTests(TestCase):
"""The list: upcoming first, then past, published only."""
@classmethod
def setUpTestData(cls):
now = timezone.now()
for title, days in [('Open lab', 0),
('Django workshop', 14),
('Python meetup', 7),
('Leeds social', -7),
('Autumn walk', -30)]:
start = now + timedelta(days=days, hours=-1)
save_event(title=title, starts_at=start)
save_event(title='Spring planning',
status=Event.Status.DRAFT)
save_event(title='Autumn social',
status=Event.Status.CANCELLED)
def test_upcoming_first_then_past(self):
with self.assertNumQueries(2):
response = self.client.get('/events/')
html = response.content.decode()
titles = ['Open lab', 'Python meetup',
'Django workshop', 'Past events',
'Leeds social', 'Autumn walk']
places = [html.index(title) for title in titles]
self.assertEqual(places, sorted(places))
self.assertNotContains(response, 'Spring planning')
self.assertNotContains(response, 'Autumn social')
def test_marks_current_and_past_events(self):
response = self.client.get('/events/')
self.assertContains(
response, 'Happening now', count=1
)
self.assertContains(response, 'event-past', count=1)
def test_empty_list(self):
Event.objects.all().delete()
response = self.client.get('/events/')
self.assertContains(response, 'No upcoming events.')
self.assertNotContains(response, 'Past events')
Each published event starts an hour before a whole number of days from now, and save_event() ends it two hours after its start. So the open lab started an hour ago and is still running, two events are to come, and two ended a week and a month ago. The first test checks the whole order in one line: each title’s position in the page must be later than the one before, and the heading “Past events” must sit between the two groups. The page may now run two queries, one for each list. The second test checks that exactly one event is marked as happening now and that the past list is marked, so a stylesheet can fade it. The third checks the new empty message.
The row partial from Chapter 12 will show each event’s date in its own time zone, so its test needs an event with times. Replace the whole EventRowPartialTests class:
events/tests.py (EventRowPartialTests, replaced)
class EventRowPartialTests(SimpleTestCase):
"""The event row partial renders one event."""
def test_row_renders_alone(self):
start = datetime(2026, 11, 19, 18, 30, tzinfo=UTC)
event = Event(pk=7, title='<b>Not a tag</b>',
starts_at=start,
ends_at=start + timedelta(hours=2),
timezone='Europe/London')
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.assertIn('Thu 19 Nov 2026, 18:30 GMT', html)
self.assertNotIn('<nav', html)
Run the event tests:
Terminal
uv run python manage.py test events
Expected result, shortened with ...:
Output
Found 34 test(s).
...
FAILED (failures=4)
Destroying test database for alias 'default'...
Four failures, all in the two changed classes: the page runs one query, has no “Happening now”, no past list, and no new empty message, and the row shows no date. Now the view. Replace event_list in events/views.py, and add the timezone import below the shortcuts import, so the top of the file reads:
events/views.py (top of the file and event_list)
"""The events app's views: one function per page."""
from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from .models import Event
def home(request):
"""Welcome visitors to Otahque."""
return render(request, 'events/home.html')
def event_list(request):
"""List published events: upcoming, then past."""
now = timezone.now()
events = Event.objects.published()
return render(request, 'events/list.html', {
'upcoming': events.upcoming(now),
'past': events.past(now),
'now': now,
})
event_detail stays as Step 5 left it. Both lists start from the same published() QuerySet, each adds its own condition and order, and neither runs until the template needs it. now goes to the template too, so it can tell which upcoming event has already started. Replace events/templates/events/list.html:
events/templates/events/list.html
{% extends "base.html" %}
{% load tz %}
{% block title %}Events | Otahque{% endblock %}
{% block content %}
<h1>Events</h1>
<ul class="event-list space-y-3">
{% for event in upcoming %}
{% partialdef event-row inline %}
<li class="event-row card border border-base-300
bg-base-100 p-4">
<a class="font-semibold"
href="{% url 'events:detail' event.id %}">
{{ event.title }}
</a>
{% timezone event.timezone %}
<span class="text-sm">
{{ event.starts_at|date:"D j M Y, H:i T" }}
</span>
{% endtimezone %}
{% if event.starts_at <= now %}
{% if now < event.ends_at %}
<span class="badge badge-primary">
Happening now
</span>
{% endif %}
{% endif %}
</li>
{% endpartialdef %}
{% empty %}
<li class="event-empty card border border-base-300
bg-base-100 p-4">No upcoming events.</li>
{% endfor %}
</ul>
{% if past %}
<h2 class="mt-8">Past events</h2>
<ul class="event-list event-past space-y-3 opacity-60">
{% for event in past %}
{% partial event-row %}
{% endfor %}
</ul>
{% endif %}
{% endblock %}
The row is still Chapter 12’s partial, defined inline where it is first used, and now shows the start in the event’s own time zone, as the detail page does. {% partial event-row %} renders the same row in the past list, so both lists look alike apart from the fade. “Happening now” needs two conditions, started and not ended, written as two {% if %} tags. {% if past %} runs the past query once and keeps the rows, so the loop below it does not query again, and the heading appears only when there is something under it. opacity-60 is Tailwind’s class for 60% opacity, which fades the whole past list; the heading says in words what the fade shows, so the difference does not rest on colour alone.
Common Error: the same instant asked twice
Writing events.upcoming(timezone.now()) and events.past(timezone.now()) calls the clock twice. An event that ends between the two calls appears in neither list, or, the other way round, in both. Call timezone.now() once, as the view does, and pass the same value to every method that needs it.
badge, badge-primary, text-sm, mt-8, and opacity-60 are new to Otahque’s templates, so the stylesheet must be built again, as in Chapter 14, beside manage.py:
Terminal
npm run build
The build ends with Done in, then a time, and site.css gains the new classes. Run the event tests:
Terminal
uv run python manage.py test events
Expected result, shortened with ...:
Output
Found 34 test(s).
...
Ran 34 tests in ...
OK
Destroying test database for alias 'default'...
Start the server with uv run python manage.py runserver and open http://127.0.0.1:8000/events/. Which section each event appears in depends on today’s date. Before 19 November 2026, the Python meetup and the Django workshop are both under “Events”; after 3 December 2026, both are under “Past events”, faded, the workshop first because it ended more recently. Either way, Spring planning and the winter social are drafts and do not appear. Stop the server with Ctrl+C.
Step 7: Give Registration a QuerySet
Open registrations/models.py. Add a class before class Registration(models.Model):, with two blank lines on each side:
registrations/models.py (1 of 2: before the class)
class RegistrationQuerySet(models.QuerySet):
"""Named questions about registrations."""
def active(self):
"""Places that members currently hold."""
return self.filter(status=Registration.Status.ACTIVE)
Then attach it, after the cancelled_at field and before class Meta::
registrations/models.py (2 of 2: after cancelled_at)
“Active” was already a rule in two places: Chapter 21’s partial unique index and the audits that searched for active rows. Now queries have a name for it too. No page calls active() yet: the page where members see their own registrations, in Chapter 31, and the capacity check, in Chapter 33, will. active() only chooses rows; it does not stop the N+1 pattern from Chapter 20 when a page then reads each registration’s member. Chapter 31 adds with_people(), a named select_related('member', 'event'), beside it, for the first page that shows names; Step 10 uses the same join inline. Ask Django whether the models need a migration, without writing one:
Terminal
uv run python manage.py makemigrations --check --dry-run
Output
No changes detected
--check makes the command fail if a migration is needed, and --dry-run stops it writing a file. A QuerySet manager without use_in_migrations is not part of the schema, so there is nothing to migrate; Chapter 18’s test_every_model_change_has_a_migration would catch it otherwise. Speed is a separate question. The pages now filter on status and ends_at and sort by starts_at and ends_at, columns with no index of their own; whether an index pays for itself is measured in Chapter 56, with explain() and real-sized data, not guessed here, because every index also slows each write a little. Run every test:
Terminal
uv run python manage.py test
Expected result, shortened with ...:
Output
Found 56 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
........................................................
...
Ran 56 tests in ...
OK
Destroying test database for alias 'default'...
Fifty-one tests from before, and five new: four for the new methods and one more for the list page, whose tests changed on purpose in Step 6.
Step 8: Show places left
Sam wants visitors to see how many places each event still has. The number is the capacity minus the active registrations, and the obvious way to show it is the wrong one. Written in the template as {{ event.registrations.active.count }}, it would run one COUNT query for every event on the list: Chapter 20’s N+1, back on the busiest page. The count belongs in the query the page already runs, as an annotation, so each list still costs one query whatever its length. The tests say so first. Add one import to events/tests.py, after from .models import Event, OrganizerAssignment:
events/tests.py (one more import)
from registrations.models import Registration
Then add a class at the end of the file:
events/tests.py (PlacesLeftTests, at the end)
class PlacesLeftTests(TestCase):
"""Places left, counted in one query, on list and page."""
@classmethod
def setUpTestData(cls):
start = timezone.now() + timedelta(days=7)
cls.meetup = save_event(starts_at=start, capacity=2)
full = save_event(title='Django workshop',
starts_at=start, capacity=1)
save_event(title='Leeds social', capacity=5,
starts_at=start - timedelta(days=30))
sai = User.objects.create_user(
'sai@example.org', display_name='Sai'
)
raj = User.objects.create_user(
'raj@example.org', display_name='Raj'
)
Registration.objects.create(event=cls.meetup,
member=sai)
Registration.objects.create(
event=cls.meetup, member=raj,
status=Registration.Status.CANCELLED,
cancelled_at=start,
)
Registration.objects.create(event=full, member=sai)
def test_with_places_counts_active_places(self):
left = {event.title: event.places_left for event
in Event.objects.with_places()}
self.assertEqual(left, {'Python meetup': 1,
'Django workshop': 0,
'Leeds social': 5})
def test_pages_show_places_left(self):
with self.assertNumQueries(2):
response = self.client.get('/events/')
self.assertContains(
response, '<span class="places text-sm">'
'1 of 2 places left</span>', html=True,
)
self.assertContains(
response, '<span class="places badge">'
'Full</span>', html=True,
)
self.assertNotContains(response, 'of 5 places left')
with self.assertNumQueries(1):
response = self.client.get(
f'/events/{self.meetup.pk}/'
)
self.assertContains(response, '1 of 2 places left')
The meetup has two places, one held by Sai and one cancelled by Raj, so one is left; the workshop’s only place is taken, so it is full; the Leeds social ended a month ago, so it shows no count. assertNumQueries holds the line on the list’s two queries and the detail page’s one. html=True compares the markup as HTML, so line breaks and indentation inside the span do not matter. Run the event tests:
Terminal
uv run python manage.py test events
Expected result, shortened with ...:
Output
Found 36 test(s).
...
FAILED (failures=1, errors=1)
Destroying test database for alias 'default'...
The error is AttributeError: 'ManagerFromEventQuerySet' object has no attribute 'with_places': the manager that as_manager() built has no such method yet. The failure is the page, which shows no places yet. Add a method to EventQuerySet in events/models.py, after past():
events/models.py (EventQuerySet, after past)
def with_places(self):
"""Add places_left: capacity minus active places."""
taken = models.Count(
'registrations',
filter=models.Q(registrations__status='active'),
)
return self.annotate(
places_left=models.F('capacity') - taken
)
Count with a filter counts each event’s active registrations, as Step 10 shows in the shell, and F('capacity') - taken asks the database to subtract, so places_left arrives on each event as a plain number. The status is written as the text 'active', because a model in events should not import from registrations, which already imports events. Now the views. Change the first line of event_list’s body to ask for the counts:
events/views.py (event_list, its second line)
events = Event.objects.published().with_places()
and replace event_detail at the end of the file:
events/views.py (event_detail, replaced)
def event_detail(request, event_id):
"""Show one published event, or 404."""
event = get_object_or_404(
Event.objects.published().with_places(), pk=event_id
)
return render(request, 'events/detail.html', {
'event': event,
'now': timezone.now(),
})
Both lists start from the annotated QuerySet, so upcoming(now) and past(now) keep their own conditions and order and gain the count. The detail page gets now too, so that it can leave the count off an event that has ended. Both pages say the same thing, so the words go in one small template, events/templates/events/places.html, beside list.html:
events/templates/events/places.html
{% if event.places_left > 0 %}
<span class="places text-sm">
{{ event.places_left }} of {{ event.capacity }} places left
</span>
{% else %}
<span class="places badge">Full</span>
{% endif %}
places_left can fall below 0 if more people hold places than the capacity allows, which Chapter 33 prevents; until then, else shows “Full” for 0 and below alike. Include it in the list row, in events/templates/events/list.html, after the {% endif %} that closes “Happening now”:
events/templates/events/list.html (in the row, after Happening now)
{% if now < event.ends_at %}
{% include "events/places.html" %}
{% endif %}
and in events/templates/events/detail.html, after the {% endtimezone %} line:
{% if now < event.ends_at %}
<p>{% include "events/places.html" %}</p>
{% endif %}
{% include %} renders another template with the same context, so event means the row’s event on the list and the page’s event on the detail page. Past events skip it on both. text-sm and badge are already in the stylesheet from Step 6, so nothing needs building. Run the event tests again:
Terminal
uv run python manage.py test events
Expected result, shortened with ...:
Output
Found 36 test(s).
...
Ran 36 tests in ...
OK
Destroying test database for alias 'default'...
Common Error: a count per row
Writing {{ event.registrations.active.count }} in the row works and shows the right numbers, and test_pages_show_places_left fails with AssertionError: 4 != 2 : 4 queries executed, 2 expected: one query for each list and one COUNT for each upcoming event. The query count is the test that catches it, because the page looks the same. Use the annotation.
Then run every test:
Terminal
uv run python manage.py test
Expected result, shortened with ...:
Output
Found 58 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
..........................................................
...
Ran 58 tests in ...
OK
Destroying test database for alias 'default'...
Step 9: Combine conditions with Q and F
Start the shell. First, name two conditions and combine them:
The first two lines are shortened here; both end <Event: Spring planning>]>. The Django workshop is virtual and Spring planning has 12 places, so either condition puts it in the first result. ~Q(status='published') is every event that is not published: the two drafts, soonest first. The third asks for drafts that are not small, and the last chains a combined condition after a named method. The repr now says EventQuerySet: every event query is built from the new class.
Common Error: a Q object after a keyword argument
Event.objects.filter(status='draft', Q(capacity__lt=20)) stops with SyntaxError: positional argument follows keyword argument. Python itself refuses the call, before Django sees it. Put the Q object first, filter(Q(capacity__lt=20), status='draft'), or combine both as Q objects.
Chapter 21 made two time rules constraints: a registration is never cancelled before it was made, and an assignment never revoked before it started. The database now refuses a new row that breaks them, but the same questions, asked as queries, are how you check rows written before a rule existed, or plan a constraint you have not added yet. Each compares two columns of the same row:
No registration was cancelled before it was made, and no assignment was revoked before it started. OrganizerAssignment has no custom QuerySet, so its repr still says QuerySet. Now write the first rule as a condition, “a cancellation is never earlier than the registration”, and look for rows that break it with exclude(), as Chapter 21’s L4 proof did:
Django shell
>>> later = Q(cancelled_at__gte=F('registered_at'))
>>> Registration.objects.exclude(later).count()
2
>>> Registration.objects.exclude(later).active().count()
2
>>> rule = later | Q(cancelled_at__isnull=True)
>>> Registration.objects.exclude(rule).count()
0
Two rows seem to break the rule, and both are active. They have no cancellation time, so cancelled_at >= registered_at is not true for them, and exclude() keeps every row where the condition is not true. The rule must say what an empty value means: “cancelled at or after registering, or never cancelled”. With that branch, no row breaks it, and it is exactly the condition of Chapter 21’s cancelled_after_registered constraint. Why the constraint needed no such care is the last quiz question. Leave the shell with exit().
Step 10: Order, count, and fetch related rows
Start the shell again. First, order, and the SQL that a QuerySet will send. str() of a QuerySet’s query gives its SQL, and Python’s textwrap.fill() folds the long line to fit the page:
Django shell
>>> import textwrap
>>> published = Event.objects.published()
>>> published.order_by('-starts_at')
<EventQuerySet [<Event: Django workshop>, <Event: Python...
>>> titles = published.values('title')
>>> print(textwrap.fill(str(titles.query), 60))
SELECT "events_event"."title" AS "title" FROM "events_event"
WHERE "events_event"."status" = published ORDER BY
"events_event"."starts_at" ASC
>>> latest = titles.order_by('-starts_at')[:1]
>>> print(textwrap.fill(str(latest.query), 60))
SELECT "events_event"."title" AS "title" FROM "events_event"
WHERE "events_event"."status" = published ORDER BY
"events_event"."starts_at" DESC LIMIT 1
The third line ends <Event: Python meetup>]>: newest first. values('title') asks for only the title column, which keeps the SQL short. ORDER BY ... ASC comes from Meta.ordering; order_by('-starts_at') replaced it with DESC, and the slice [:1] became LIMIT 1, so the database returns one row. The value appears as published without quotes because str(query) is only a picture of the SQL: the real statement sends the value separately, and the database driver quotes it. Copy SQL from str(query) only to read it, never to run it.
Next, count. Name the condition “the registration is active”, seen from an event, and count each event’s matching registrations:
Django shell
>>> from django.db.models import Count, F, Q
>>> active = Q(registrations__status='active')
>>> counted = Event.objects.annotate(
... places=Count('registrations', filter=active)
... )
>>> counted.ordered
False
>>> for event in counted.order_by('starts_at'):
... print(event.title, event.places)
...
Python meetup 1
Django workshop 1
Winter social 0
Spring planning 0
>>> Registration.objects.aggregate(
... total=Count('id'),
... active=Count('id', filter=Q(status='active')),
... )
{'total': 3, 'active': 2}
registrations__status reads from the event across Chapter 20’s reverse relation. The meetup has two registrations, but Raj’s is cancelled, so it counts 1. ordered is False, because a grouped query does not use Meta.ordering; the loop adds order_by('starts_at') to get date order back. aggregate() returns a dictionary, not a QuerySet: three registrations in all, two of them active.
Now two of Chapter 21’s audits as single queries. Its duplicate search fetched pairs and counted them with Counter; here the database groups and counts. values() before annotate() groups the rows by the listed fields, one result per pair:
No pair holds more than one active place, as Chapter 21’s constraint guarantees. The second query compares each event’s count of active places with its own capacity, with F: none is over. alias() computes the count for the filter without adding it to each event. This is an audit, not a guard: two members could still take the last place together, which Chapter 33 prevents.
Last, related rows. A Prefetch object combines Chapter 20’s two loading methods with this chapter’s named method:
Django shell
>>> from django.db.models import Prefetch
>>> from django.test.utils import CaptureQueriesContext
>>> people = Registration.objects.active().select_related(
... 'member'
... )
>>> places = Prefetch('registrations', queryset=people,
... to_attr='active_places')
>>> with CaptureQueriesContext(connection) as queries:
... for event in published.prefetch_related(places):
... names = [place.member.display_name
... for place in event.active_places]
... print(event.title, names)
...
Python meetup ['Sai']
Django workshop ['Sai']
>>> len(queries)
2
Two queries for the whole loop: one for the published events, and one for their active registrations, joined with their members. With a hundred events it would still be two. to_attr stores each event’s prefetched rows as a plain list, so event.active_places has no filter() or all(). connection is the database connection, imported by the shell. Leave the shell with exit().
Step 11: Review and commit
Look at what changed:
Terminal
git status --short
Output
M events/models.py
M events/templates/events/detail.html
M events/templates/events/list.html
M events/tests.py
M events/views.py
M registrations/models.py
M registrations/tests.py
M static/otahque/site.css
?? events/templates/events/places.html
Eight changed files, one new template, and no new migration. The shell steps changed no rows. Commit:
Terminal
git add events registrations static
git commit -m "Add QuerySets, past events, and places left"
When something goes wrong
Table 22.2 — Query problems and safe recovery
Symptom
Likely cause
Safe recovery
Found 55 test(s), FAILED (errors=4)
The methods do not exist yet
Expected in Step 3; continue with Step 4
Found 36 test(s), FAILED (failures=1, errors=1) in Step 8
Work through Table 22.3 from the folder that holds manage.py. The test rows come first: they hold the behaviour in place, whatever rows your database holds.
Table 22.3 — Verification checklist for Chapter 22
Check
Command or action
Expected result
Red stage seen
The Step 3 run, before the methods
Found 55 test(s); FAILED (errors=4)
Tests pass
uv run python manage.py test
Found 58 test(s); OK
List test changed first
The Step 6 run, before the view
Found 34 test(s); FAILED (failures=4)
No migration needed
makemigrations --check --dry-run
No changes detected
One rule in the views
git grep -n -o Status.PUBLISHED events/views.py
No output
List page
runserver; open /events/
Upcoming events first, each with its places left; ended ones under Past events, faded
Places in the list's queries
test_pages_show_places_left
2 queries on the list, 1 on the detail page
Detail page unchanged
A draft's address
404
Counts in one query
Step 10's annotate() loop
1, 1, 0, 0 for the four events
Prefetch
Step 10's CaptureQueriesContext
2 queries
Committed
git status --short
No output
Not verified
macOS, Linux, WSL; PostgreSQL
Readers on those systems; Chapter 32
The git grep check prints nothing once both views use published(), and git grep then exits with status 1, which means “no match”, not an error. The commands were checked in Windows PowerShell 5.1 and Git Bash, with the shell sessions typed into a Windows console. PostgreSQL writes the same FILTER (WHERE ...) clause; Chapter 32 runs these tests there.
Que. 2 Why does Event.objects.filter(location='Virtual').published() work, while User.objects.filter(is_staff=True).create_user(...) fails?
Flip to check your answerFold answer back
Answer. published() is a method of EventQuerySet, and filter() returns an EventQuerySet, so the method is there. create_user() is a method of UserManager only; filter() returns a QuerySet, which does not have it, so Python raises AttributeError.
Que. 3 The detail view now passes Event.objects.published() to get_object_or_404(). What does a visitor see at a draft’s address, and how do you know nothing else changed?
Flip to check your answerFold answer back
Answer. A 404 page, as before: the shortcut calls get() on the published events only, finds nothing, and raises Http404. Chapter 19’s detail-page tests, unchanged, still pass.
Que. 4 For the Python meetup, Count('registrations') gives 2, but Count('registrations', filter=Q(registrations__status='active')) gives 1. Why?
Flip to check your answerFold answer back
Answer. The meetup has two registrations: Sai’s, which is active, and Raj’s, which is cancelled. The filter argument counts only the related rows that match, so Raj’s is left out.
Que. 5 In Step 10, the annotated events came back with ordered False, although Event has Meta.ordering. Why, and what fixes it?
Flip to check your answerFold answer back
Answer. An annotation over a relation groups rows with GROUP BY, and Django does not apply the model’s default ordering to grouped queries. Add an explicit order_by('starts_at').
Que. 6 In Step 9, exclude(later) counted two active registrations as breaking the rule. Chapter 21’s constraint cancelled_after_registered stores them without complaint. Why the difference, and why does the constraint still spell out Q(cancelled_at__isnull=True)?
Flip to check your answerFold answer back
Answer. The two treat an empty value differently. A comparison with NULL is neither true nor false. filter() keeps only rows where the condition is true, and exclude() keeps the rest, so the active rows, with no cancellation time, are counted as breaking it. A CHECK refuses only rows where the condition is false, so the database passes them, and on Django 6.1 full_clean() does the same. The isnull branch therefore changes nothing for the database; it states the intent, “never cancelled, or cancelled at or after registering”, so that a reader, and anyone who turns the condition into a query, gets the same answer as the constraint.
Mini-Challenge
Que. 7 Sam asks for the published events that take place in person, not online, and have at least one active place, latest first. Write it as one chained query in the shell, starting from published(), and predict the result before running it.
Flip to check your answerFold answer back
Answer. Only the Python meetup: the Django workshop is virtual. One query that answers it:
The parentheses around the whole chain let it span several lines. Each method returns a new QuerySet, so the order of exclude() and alias() does not matter here, but filter(places__gte=1) must come after the alias() that defines places, and order_by() is needed because the count groups the rows. An answer using annotate() instead of alias() is also correct; it adds places to each event as well.
What We Learned
A manager starts queries; a QuerySet method can be called anywhere in a chain. Methods that select rows belong on a custom QuerySet, attached with as_manager().
Moving a repeated rule into published() is a refactor: the page tests, unchanged, prove the pages behave the same and run the same queries.
A method that depends on the time takes now as an argument, so tests can fix the clock and a page uses one instant; upcoming(now) and past(now) split the list at that instant.
A deliberate change to what a page shows starts by changing the test that describes it.
A number shown for every row belongs in the query as an annotation, such as with_places(); computed per row in the template, it is an N+1.
get_object_or_404() accepts a QuerySet, so a detail view can look among published events only.
Q objects combine conditions with &, |, and ~; F compares one column with another, row by row.
A comparison with an empty value is not true, so exclude() returns rows with NULL; a rule must say what empty means.
order_by() replaces the model’s ordering; grouped queries ignore Meta.ordering, so add order_by() when the order matters.
annotate() adds a count to each row, aggregate() returns one dictionary, and Count(filter=...) counts only matching related rows.
Prefetch with a named QuerySet and to_attr loads exactly the related rows a page needs, in one extra query.
Key terms
Use Table 22.4 to explain this chapter’s ideas in your own words.
Table 22.4 — Key terms from Chapter 22
Term
Meaning
Manager
The object that starts queries, such as Event.objects.
Custom QuerySet
A QuerySet subclass with named methods that refine queries.
as_manager()
Builds a manager carrying a QuerySet's methods.
Refactor
A change to how code is written that keeps its behaviour.
Q object
A condition kept as a value, combined with &, or (|), and ~.
F expression
A reference to a column's value, used in a query.
NULL
The database's empty value; comparisons with it are not true.
Aggregate
A value computed from many rows, such as Count.
annotate()
Adds an aggregate to each row of a QuerySet.
aggregate()
Computes aggregates over a whole QuerySet, as a dictionary.
alias()
Defines a value for filtering without returning it.
Prefetch
Chooses the QuerySet and attribute for prefetched rows.
Readiness checkpoint: you are ready for Chapter 23 when all 58 tests pass, makemigrations --check --dry-run prints No changes detected, the list page shows upcoming events first, with their places left, and ended ones under Past events, faded, a draft’s address returns 404, Step 10’s counts match your rows, and git status --short prints nothing. Chapter 23 opens the admin site, which uses Event.objects and therefore sees drafts: one reason this chapter kept the default manager unfiltered. Return to the relevant step if any result is missing.
Git Commit
Your Chapter 22 work was committed in Step 11. For the record, these were the commands, in any of the four shells, beside manage.py:
Terminal
git add events registrations static
git status --short
Output
M events/models.py
M events/templates/events/detail.html
M events/templates/events/list.html
A events/templates/events/places.html
M events/tests.py
M events/views.py
M registrations/models.py
M registrations/tests.py
M static/otahque/site.css
Terminal
git commit -m "Add QuerySets, past events, and places left"
The commit holds two QuerySet classes, two changed views, the list and detail templates, the new places template, the rebuilt stylesheet, seven new tests, and the changed list-page tests. There is no migration, because nothing in the database’s schema changed.
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 23, 36, and 57. They are extension questions, not a gate to the next chapter. Each code proof 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 only read your rows.
L1 (Junior): What is the difference between a manager and a QuerySet, and where would you put a published() method?
What the interviewer is testing: Do you know what each object is for, and why a selecting method must be chainable?
Flip to check your answerFold answer back
Perfect answer: A manager, such as Event.objects, is the model’s entry point for queries; Django adds a plain one called objects unless the model defines its own. A QuerySet is a lazy description of a query, and every refining method, such as filter(), returns a new QuerySet of the same class. A method on a manager is available only at the start, so it cannot follow filter(). A method on a custom QuerySet is available everywhere in the chain, and as_manager() copies it onto the manager too. So published() goes on an EventQuerySet, attached as objects = EventQuerySet.as_manager(). Manager methods are right for things that do not refine a query, such as create_user(). I would add published() because two views already repeat the rule, and I would keep objects itself unfiltered.
Table 22.5 — Managers and QuerySets compared
Aspect
Manager
QuerySet
Example
Event.objects
Event.objects.filter(...)
Custom methods
Start of a chain only
Anywhere in a chain
Typical use
Creating rows
Selecting rows
Behind the scenes:
managers and QuerySets (summary)
Event.objects -> ManagerFromEventQuerySet
Event.objects.filter(...) -> EventQuerySet
.published() -> EventQuerySet, one more WHERE
User.objects.create_user -> manager only, not chainable
Code proof: a QuerySet method after filter(), and a manager method that cannot follow it:
../practice/l1_chain.py
import setup_django
from accounts.models import User
from events.models import Event
virtual = Event.objects.filter(location='Virtual')
print(virtual.published())
try:
User.objects.filter(is_staff=True).create_user
except AttributeError as error:
print(error)
Output
<EventQuerySet [<Event: Django workshop>]>
'QuerySet' object has no attribute 'create_user'
published() refines a filtered query, and create_user does not exist once filter() has returned a QuerySet.
Common mistakes:
Writing selecting methods on a Manager subclass, so they cannot be chained.
Overriding get_queryset() on objects to hide rows, which hides them from the admin site too.
Adding a method for every condition used once.
Follow-up the interviewer might ask:
“When would you use Manager.from_queryset() instead of as_manager()?”
“Why is delete() not copied onto the manager?”
L2 (Mid-Level): Why can filter(a, b) and filter(a).filter(b) return different events when both conditions are about registrations?
What the interviewer is testing: Do you understand how conditions across a multi-valued relationship are joined?
Flip to check your answerFold answer back
Figure 22.4 — Conditions across a reverse relation: one call or two.
Perfect answer: An event has many registrations, so a condition such as registrations__status='active' asks whether some registration matches. Inside one filter() call, all the conditions on that relation must hold for the same registration: “an event where Raj has an active registration”. In chained calls, Django joins the registrations table once for each call, and each condition may be met by a different registration: “an event where Raj has some registration, and some registration is active”. At the Python meetup, Raj’s place is cancelled and Sai’s is active, so the first question finds nothing and the second finds the meetup. The chained form can also return the same event more than once. I choose the form that matches the question, use one call or a Q object for “the same related row”, and check with a test. exclude() has its own rules for multi-valued relations, so for “events without an active registration by Raj” I would exclude using a subquery of registrations.
Behind the scenes:
multi-valued conditions (summary)
filter(a, b) -> one JOIN; same related row
filter(a).filter(b) -> two JOINs; rows may differ
duplicates -> possible with chained JOINs
Code proof: the two forms, asked about Raj:
../practice/l2_relations.py
import setup_django
from events.models import Event
raj = {'registrations__member__email': 'raj@example.org'}
active = {'registrations__status': 'active'}
print(Event.objects.filter(**raj, **active))
print(Event.objects.filter(**raj).filter(**active))
**raj unpacks the dictionary into keyword arguments. Raj has no active place anywhere, but the meetup has a registration of his and an active registration of Sai’s.
Common mistakes:
Treating chained filters on a relation as the same as one call.
Fixing duplicate events with distinct() without asking why they appeared.
Assuming exclude() mirrors filter() for multi-valued relations.
Follow-up the interviewer might ask:
“How would you write ’events where Raj has no active place’ correctly?”
“Why do chained filters on a forward foreign key behave the same as one call?”
L3 (Senior): A report counts each event’s registrations and organizers in one annotate(), and both numbers are too high. Why, and how do you fix it?
What the interviewer is testing: Can you see the joins behind an aggregation and choose a correct fix?
Flip to check your answerFold answer back
Figure 22.5 — Why two counts in one query grow, and how to fix them.
Perfect answer:annotate(places=Count('registrations'), organizers=Count('organizer_assignments')) joins both tables to events in one query. Each event’s row is repeated once for every combination of a registration and an assignment, and each COUNT counts the repeated rows. The meetup has two registrations and one assignment, so the join has two rows, and the organizer count is 2 instead of 1; with more of each, both counts grow. For Count, distinct=True counts each related row once. For Sum or Avg, distinct gives wrong answers too, so I would compute each aggregate in its own subquery, with Subquery and OuterRef, which Chapter 55 covers, or run two queries. I would also write a test with known counts, and read the SQL with str(queryset.query) when in doubt.
Behind the scenes:
two counts (summary)
JOIN registrations and assignments -> rows multiply
Count(..., distinct=True) -> each row once
Sum over two joins -> subqueries
Code proof: the meetup’s two counts, without and with distinct:
../practice/l3_counts.py
import setup_django
from django.db.models import Count
from events.models import Event
meetup = Event.objects.filter(title='Python meetup')
for distinct in (False, True):
row = meetup.annotate(
places=Count('registrations', distinct=distinct),
organizers=Count('organizer_assignments',
distinct=distinct),
).get()
print(distinct, row.places, row.organizers)
Output
False 2 2
True 2 1
The registrations count is 2 both times, Sai’s and Raj’s places, because the meetup has one assignment. The organizer count doubles without distinct, one row for each registration.
Common mistakes:
Trusting a report’s numbers without a test that knows the answer.
Adding distinct=True to a Sum, which merges equal values.
Using annotate() over two relations for a page that shows both counts.
Follow-up the interviewer might ask:
“How would you write the organizer count as a subquery?”
“Would the counts be wrong if one relation were a forward foreign key?”
L4 (Staff): A teammate proposes making Event.objects return only published events, so that no view can forget the rule. What do you advise?
What the interviewer is testing: Do you know which manager Django’s own tools use, and the cost of hiding rows by default? This looks ahead to Chapters 23 and 30.
Flip to check your answerFold answer back
Figure 22.6 — Why the default manager stays unfiltered.
Perfect answer: The goal is right; the mechanism is wrong. The first manager a model defines is its default manager, _default_manager, and Django’s tools use it: the admin site lists rows with it, dumpdata exports with it, and the reverse managers of related models are built from its class. If objects overrode get_queryset() to return published events only, the administrator could not see or correct drafts in Chapter 23’s admin site, backups would miss drafts, and a registration’s reverse queries would silently skip rows. Following a foreign key, such as registration.event, uses the plain base manager, so the same object would be visible one way and invisible the other. I would keep objects whole and make the rule explicit with Event.objects.published(), as Otahque does. To stop a view forgetting it, I would give every public page a test with a draft and a cancelled event, review new pages against that rule, and, in Chapter 30, check permissions as well. If a filtered manager is truly wanted, it is a second manager with its own name, declared after objects, as some tutorials do with published.
Behind the scenes:
managers Django uses (summary)
_default_manager -> first manager: admin, dumpdata
reverse managers -> subclass the default's class
_base_manager -> plain Manager: registration.event
rule -> keep objects whole; name the filter
Code proof: which manager each path uses, in the reader’s project:
../practice/l4_managers.py
import setup_django
from events.models import Event
from registrations.models import Registration
print(Event._meta.default_manager.name)
print(type(Event._base_manager).__name__)
place = Registration.objects.active().first()
related = place.event.registrations
print(type(related).__mro__[1].__name__)
print(related.active())
The last line is shortened; it ends Python meetup>]>. __mro__ lists a class’s parents in order, so its second entry shows that the reverse manager place.event.registrations was built from Registration’s default manager class, which is why active() works on it. The base manager is Django’s plain Manager.
Common mistakes:
Filtering the default manager and discovering it in the admin site.
Assuming related access and queries use the same manager.
Treating a code convention as a guarantee without per-page tests.
Follow-up the interviewer might ask:
“What does Meta.default_manager_name change?”
“How would you find every public view that does not use published()?”
L5 (Lead): Should Otahque wrap the ORM in a repository layer, so that views never build queries themselves?
What the interviewer is testing: Can you weigh an architecture pattern against what the framework already provides, and set a boundary the team can follow? This looks ahead to Chapters 36 and 55 to 57.
Flip to check your answerFold answer back
Figure 22.7 — A boundary for query code.
Perfect answer: A repository, a class whose methods return rows, such as EventRepository.published_in_person_soonest_first(), is meant to give each query one home and to hide the database from the rest of the code. With Django, a custom QuerySet already does the first, and the second costs more than it saves. A repository that returns lists ends the chain: the view can no longer add order_by(), a slice, select_related(), or Chapter 36’s pagination, which needs a QuerySet to count and slice in the database. So the repository grows a method or a parameter for every combination. Named QuerySet methods compose instead: Event.objects.published().exclude(location='Virtual')[:10] stays one query. Repositories are common in FastAPI projects for a good reason: their usual ORM, SQLAlchemy, follows the Data Mapper pattern, where plain classes are loaded and saved through a session that code must pass around, and nothing gives queries a built-in home, so a repository class holds the session and the named queries. Django follows Active Record, as its design philosophy says: a model carries its own data and behaviour, and its manager and QuerySet already are that home. My boundary for the team is “fat models, thin views”: rules about which rows are selected live in QuerySet methods; actions on a record live in model methods, such as registration.cancel() in Chapter 31 or event.register(member), with its capacity check inside a transaction, in Chapter 33; views only read the request, call one method, and choose a response. If a model grows too large, or an action has no single owning model, I extract that action into a small service module, on evidence rather than in advance, and record the decision.
Behind the scenes:
query boundary (summary)
which rows -> QuerySet methods, on the model
what happens -> model methods (fat models)
views -> thin: request in, one call, response
repository -> lists end the chain; Django has one
Code proof: a named method sliced, and the SQL that the database receives:
../practice/l5_slice.py
import textwrap
import setup_django
from django.db import connection
from django.test.utils import CaptureQueriesContext
from events.models import Event
with CaptureQueriesContext(connection) as queries:
first = list(Event.objects.published()[:1])
print(first)
sql = queries[0]['sql']
print(textwrap.fill(sql[sql.index('WHERE'):], 60))
Output
[<Event: Python meetup>]
WHERE "events_event"."status" = 'published' ORDER BY
"events_event"."starts_at" ASC LIMIT 1
The slice became LIMIT 1, so the database returned one row; a method that returned a list would have fetched every published event first. The captured SQL quotes 'published', unlike str(query), because it shows the statement as the database ran it.
Common mistakes:
Copying a pattern another stack needs, such as a FastAPI repository over SQLAlchemy, into Django, where QuerySets already fill that role.
Returning lists from query helpers, so pagination fetches every row.
Putting actions in views, where the admin, the shell, and tests cannot reuse them, or in QuerySet methods, where transactions are hard to see.
Follow-up the interviewer might ask:
“What would make you add a repository after all?”
“Where does a function that registers a member and checks capacity belong?”
Next: Chapter 23 opens Django’s admin site, the administrator’s tool for checking and correcting accounts, events, registrations, and organizer assignments through a browser, using the objects managers this chapter kept whole.