ContentsClose contents
Pre-release
Chapter 20 · Relationships between models: registrations and organizersCHAPTER 20

Complete six-part pre-release for review. Public pages are unchanged; the rule of one active registration per member and event arrives in Chapter 21.

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

Relationships between models: registrations and organizers

Stage 3: Data and the database (Chapters 15 to 23)

Prerequisites: Chapters 4, 7, and 15 to 19, including the Chapter 19 project, its 30 passing tests, its three events, and the local superuser from Chapter 18

What you’ll build: A new registrations app and two connected models, Registration and OrganizerAssignment, whose foreign keys refuse to delete history, explored in the Django shell and proved by tests written first.

Why This Matters

Sai wants a place at Sam’s Python meetup in Leeds. Raj wants one too, and he may cancel later. Sam runs the meetup, and one day another member may run it with him, or take over from him. Since Chapter 19, the events page reads real rows from the database, but those rows stand alone. Nothing in the database can say “Sai has a place at this event” or “Sam organizes it”, because no table points at another.

Chapter 15 drew the answer as an ERD, an entity relationship diagram. Two of its entities, Event and Member, are tables now: events_event since Chapter 18, and accounts_user for members. The other two, Registration and Organizer assignment, are the lines between them made into rows. Each holds a key to one event and a key to one member, plus facts of its own: when Sai registered, whether her place is active or cancelled, and when Sam’s assignment was revoked, if it ever is. Without these rows there is nothing to register, confirm, cancel, or count.

This chapter builds both, in Django’s terms. A relationship field on a model becomes a foreign key in the database and an attribute in Python, so that booking.event is an event object and meetup.registrations lists every registration for the meetup. You choose what happens when someone tries to delete an event or a member that registrations point at, and you see Django refuse. You also meet the most common performance mistake with related rows, one database query for every row in a loop, and remove it with one call.

By the end of the chapter, you will be able to:

  • choose between ForeignKey, OneToOneField, and ManyToManyField for a relationship described in words;
  • declare a foreign key to a model in another app, and to the user model through settings.AUTH_USER_MODEL;
  • choose an on_delete rule from what the data means, and explain what PROTECT and CASCADE each do;
  • follow a relationship in both directions, and name the reverse direction with related_name;
  • filter across relationships with two underscores, and recognize when that repeats a row;
  • count the queries a loop over related rows runs, and reduce them to one with select_related().

The public pages do not change in this chapter: visitors still see published events, and nothing about who registered or who organizes. Whether an event page should name its organizers is a product decision, recorded for later. The rule that a member holds at most one active registration per event, and other rules the database itself should enforce, are Chapter 21. Named query methods are Chapter 22, the admin site Chapter 23, and the pages where members register and cancel Chapter 31.

PAGE 001

What You Need to Know

Relationship fields

Chapter 15 read relationships aloud: “one event has zero or more registrations; each registration belongs to exactly one event.” It drew the key on the many side, the registration, pointing at the one side, the event. Django turns that sentence into one field.

New Concept: relationship fields

What problem exists? A registration must refer to one event and one member. Storing the event’s title or the member’s email in the registration would copy facts that can change, and nothing would stop a registration from naming an event that does not exist.

What did people do before? They added an integer column, such as event_id, wrote the SQL FOREIGN KEY clause by hand, as you did in Chapter 15, and fetched the related row with a second query whenever they needed it.

What is a relationship field? A field on a model whose value is another model’s row. ForeignKey is the many-to-one kind: many registrations, one event. It becomes a column named after the field plus _id, such as event_id, holding the other row’s primary key, with a database foreign-key constraint and an index. OneToOneField is a foreign key that is also unique, so each row on the other side has at most one partner. ManyToManyField connects many rows to many rows through a third table that Django creates for you.

Why use one? The database refuses a key that points at nothing, the index makes lookups by event fast, and Python gets objects instead of numbers: booking.event is an Event, loaded when you ask for it.

Now let’s use it. Steps 3 and 4 write two models with two foreign keys each.

Table 20.1 compares the three fields. Otahque uses only ForeignKey in this chapter, because both new entities are rows with their own facts that point at two others.

Table 20.1 — Django’s three relationship fields
Field Read aloud Where the key lives
ForeignKey Many registrations, one event An event_id column on the many side
OneToOneField One member, at most one profile A unique key column on one side
ManyToManyField Many members, many groups A third table holding pairs of keys

You already have two many-to-many relationships, though you have not written one. Chapter 17’s user model inherits groups and user_permissions from PermissionsMixin, and Chapter 18’s sqlmigrate showed their link tables, such as accounts_user_groups, each row one pair of keys. A many-to-many field suits a link with no facts of its own. A registration has facts of its own, its status and its times, so Chapter 15 made it an entity, and here it becomes a model with two foreign keys. Django can treat such a model as the link table of a many-to-many field, through an option called through, but nothing in this chapter needs it.

A one-to-one field suits extra facts about exactly one row, such as a member profile beside the account. Otahque has no profile entity: the display name lives on the user model itself, and Chapter 27 decides whether a profile is needed. If it were, it would look like this, as an illustration only:

class Profile(models.Model):
    member = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    bio = models.TextField(blank=True)

From the member’s side, sam.profile would be his profile. For a member with none, it raises RelatedObjectDoesNotExist, a kind of Profile.DoesNotExist, with the message User has no profile.

What happens on delete

Every foreign key forces a decision before Django accepts it: what should happen to the registrations when someone deletes the event they point at?

New Concept: the on_delete rule

What problem exists? Deleting an event that registrations point at would leave rows whose event_id names nothing. The database refuses that, so something must happen to them first.

What did people do before? They wrote ON DELETE clauses in their SQL, or deleted the dependent rows by hand before the parent, or forgot, and found orphaned rows later.

What is on_delete? A required argument of ForeignKey and OneToOneField that names the rule. models.CASCADE deletes the dependent rows too. models.PROTECT refuses the whole delete with a ProtectedError. models.SET_NULL empties the key, which the column must allow with null=True. Table 20.2 lists the common rules.

Why does it matter? The rule is a statement about what the data means. A registration records that Sai registered; deleting it erases history that Chapter 2’s cancellation rules and Chapter 15’s ERD both keep. So Otahque protects it.

Now let’s use it. Step 4 writes on_delete=models.PROTECT on all four keys, and Step 6 tries to delete the meetup.

Table 20.2 — Common on_delete rules
Rule When the referenced row is deleted Suits
CASCADE Dependent rows are deleted too Rows that are part of their parent
PROTECT The delete is refused: ProtectedError Records that history needs
SET_NULL The key is emptied (needs null=True) Optional links
RESTRICT Refused, like PROTECT, with one exception for cascades Rare cases; read the documentation first
DB_CASCADE The database deletes them; Django sends no signals Many rows, new in Django 6.1

Many tutorials use CASCADE everywhere. For Otahque’s registrations it would be wrong: deleting a cancelled event would silently erase every record that anyone registered for it. PROTECT has a cost too: a member who has registrations cannot be deleted either. How a member closes their account while history is kept is a question for Chapters 27 and 65, and this chapter’s L5 interview question looks ahead to it.

What Step 6 will see when it tries to delete the meetup is drawn in Figure 20.1.

Four numbered cards in a row. An orange card, meetup.delete(), asked in the shell, leads to a purple Collector card, Django finding every row that points at the event, then a purple PROTECT card, the rule on both foreign keys that point at the event, then a red ProtectedError card, raised before any DELETE is sent. Below, a zone headed Kept, nothing was deleted, holds four green cards: the Python meetup event, Sai’s active registration, Raj’s active registration, and Sam’s organizer assignment. Beside it, a grey dashed card headed With CASCADE instead says the event, both registrations, and the assignment would all be deleted, with no record that Sai and Raj ever registered.
Figure 20.1 — PROTECT refuses to delete an event that registrations and an assignment point at.

Under the Hood: what a relationship becomes

In the database, event = models.ForeignKey(...) becomes a column, event_id bigint NOT NULL, with REFERENCES "events_event" ("id") and a CREATE INDEX on it; Step 5 reads both in the SQL. On SQLite, Django declares the constraint DEFERRABLE INITIALLY DEFERRED: the database checks it when the transaction commits, not on each statement. So Registration.objects.create(event_id=999, ...) inside a transaction appears to succeed, and the IntegrityError arrives at the commit. In the shell, each line commits at once, so you see the error immediately; inside a test or an atomic block, it arrives at the end. The on_delete rules in Table 20.2 other than the DB_ ones are not SQL at all. When you call delete(), Django’s deletion collector first queries every model with a foreign key to the row, applies each rule in Python, and only then sends DELETE statements, wrapped in one transaction. PROTECT raises its error during collection, before any DELETE is sent. Django 6.1’s DB_CASCADE, DB_SET_NULL, and DB_SET_DEFAULT instead write the rule into the table as SQL ON DELETE, so the database does the work without loading the rows; the price is that Django sends no pre_delete or post_delete signals for those rows.

Two directions

A foreign key is declared on one model, but you can follow it from both ends.

New Concept: forward access, reverse access, and related_name

What problem exists? Given a registration, you need its event. Given an event, you need its registrations. The key is stored only on the registration.

What did people do before? One direction read the key and fetched one row; the other ran a query for every row whose key matched, written by hand.

What are they? Forward access follows the field: booking.event is the event, and booking.event_id is the raw number, with no query. Reverse access starts from the other side: Django adds a related manager to Event, a manager limited to one event’s registrations, so meetup.registrations.all() and meetup.registrations.count() work like Event.objects, for this event only. The manager’s name comes from the field’s related_name argument. Without it, Django names it after the model, lowercased, plus _set: registration_set.

Why name it? meetup.registrations reads better than meetup.registration_set, and when two models point at the same model, as both new models point at the user, each needs its own clear name: sai.registrations and sam.organizer_assignments.

Now let’s use it. Step 6 follows both directions in the shell.

The four tables, the app that owns each model, and the reverse name on each relationship are drawn in Figure 20.2.

Three zones side by side, one per app. The accounts zone holds a green User (Member) table with id as primary key, email as unique key, and display_name. The events zone holds a green Event table, with id, title, starts_at, and status, and below it an orange OrganizerAssignment table with id, event_id and member_id as foreign keys, assigned_at, and revoked_at. The registrations zone holds an orange Registration table with id, event_id and member_id as foreign keys, status, registered_at, and cancelled_at. Blue arrows run from each foreign key row to the table it refers to: Registration to Event and to User, each labelled registrations, and OrganizerAssignment to Event and to User, each labelled organizer_assignments.
Figure 20.2 — The four tables, the apps that own them, and the reverse name of each relationship.

The double underscore from Chapter 19’s lookups also follows relationships. Registration.objects.filter(event__location='Virtual') follows the foreign key forwards and compares the event’s location. Event.objects.filter(registrations__member=sai) follows it backwards, using the related_name, and finds every event Sai has registered for. Django writes the SQL JOIN for you.

A reverse filter has one surprise. It joins each event to its registrations, so an event with two matching registrations appears twice in the result. distinct() removes the repeats. Step 6 shows both.

Prefer the setting, or get_user_model()?

Chapter 17 said that other code should not import accounts.User directly, so that the project can name its user model in one place. In a relationship field, use the setting: models.ForeignKey(settings.AUTH_USER_MODEL, ...). It is a string, 'accounts.User', which Django resolves after every model is loaded, so the import order of apps does not matter. In code that runs later, such as tests, views, and scripts, use get_user_model(), from django.contrib.auth, which returns the class itself. Both follow AUTH_USER_MODEL, and Django’s documentation recommends exactly this split.

Where the new models live

Chapter 7 created the events app with startapp and said that an app groups one area of the product. Registration is about to become a large area: Chapter 31 adds the pages where members register and cancel, and Chapter 46 a waitlist. This is the app that Chapter 7’s boundary record, Table 7.3, planned for this chapter. It gets its own app now, registrations, so that its model never has to move between apps after its table holds data, which needs careful migrations. Organizer assignment stays in events: it records who runs an event, and Chapter 30’s organizer access reads it from the event’s side.

A model can name a model in another app with a string, 'events.Event': the app label, a dot, and the class name. Like the user setting, the string is resolved after all models load, so registrations/models.py does not need to import events.models. Inside the events app, OrganizerAssignment can name Event directly, because the class is defined above it in the same file.

Try it yourself

Que. 1 An organizer wants to attach any number of topics, such as “Python” and “Data”, to an event, and each topic can label many events. A topic link has no facts of its own. Which relationship field fits, and where would its data live?

Flip to check your answerFold answer back

Answer. ManyToManyField, because many events relate to many topics and the link holds nothing but the pair. Django would create a third table holding one row per pair of keys, like accounts_user_groups. If the link later needed its own facts, such as who added the topic, it would become a model with two foreign keys, as Registration is. Topics are not in Otahque’s first release, so the project has none; the optional lab in Step 9 builds them in a copy, so that you can see the third table.

One query per row

Following a relationship is so easy that it hides its cost. The queries one loop over three registrations runs, and the single query that replaces them, are drawn in Figure 20.3.

Two zones. The left zone, headed Registration.objects.all(), lists seven numbered query cards: a green first card, SELECT the registrations, then six red cards fetching member Sai, event Python meetup, member Raj, event Python meetup, member Sai, and event Django workshop, and a red total card, 7 queries, 1 for the list, then 2 for each of 3 rows. The right zone, headed select_related(...), holds a purple card numbered 1, One query, SELECT the registrations INNER JOIN events_event INNER JOIN accounts_user, and an arrow down to a green card, 1 query, however many rows the loop prints.
Figure 20.3 — The same loop, without and with select_related().

Under the Hood: lazy related objects and select_related()

A registration loaded from the database holds event_id and member_id, not the event or the member. The first time code reads booking.event, Django runs a query for that one event and caches it on that registration object; reading it again costs nothing. In a loop over many registrations, each one fetches its own event and its own member, so three registrations cost one query for the list and two for each row: seven. With a hundred rows it is two hundred and one. This pattern is called N+1: one query plus one more for each of N rows. select_related('event', 'member') tells the QuerySet to fetch the event and the member in the same query, with SQL INNER JOINs, and to build all three objects from each joined row: one query, however many rows. It follows forward foreign keys and one-to-one fields. For the reverse direction, such as every event with its registrations, prefetch_related('registrations') runs one more query for all the registrations at once and hands each event its own. Django 6.1 also adds fetch modes: fetch_mode(FETCH_PEERS) fetches a related object for every row of the QuerySet the first time any row asks, and fetch_mode(FETCH_RAISE) raises FieldFetchBlocked instead of querying, which makes an N+1 fail loudly. This book uses them only as a reference until Chapter 57 sets a policy.

Step 7 counts both versions on your own rows, and adds prefetch_related() for the reverse direction.

In practice: refusing to delete history

Situation. An organizer tidies up and deletes an old event that had forty registrations. Months later, a member asks for confirmation that they were registered, or the community wants to know how many people registered for its first year of events.

Application. With PROTECT on the registrations’ event key, the delete is refused, and the error names the rows that hold it. The organizer cancels the event instead, which changes its status and keeps every registration, as Chapter 2’s rules intend.

Consideration. Refusing deletes moves the decision to the people who own the data. Some rows should eventually go, such as personal details after an agreed time. That needs a stated retention rule and a deliberate process, Chapters 41 and 65, not a cascade that runs whenever someone deletes a parent row.

PAGE 002

How We Build It

Start from Chapter 19, in the folder containing manage.py, with your own .env, the locked environment, 30 passing tests, every migration applied, the local superuser from Chapter 18, and three events: two published and one draft. Step 2 creates a new app, registrations, and installs it in config/settings.py. Steps 3 to 5 write the tests first, then registrations/models.py, add a model to events/models.py, and create two migrations. Steps 6 and 7 work in the Django shell and add rows: two members, one organizer assignment, and three registrations. At the end of Step 8, 36 tests pass, every migration is applied, the public pages are unchanged, and the work is committed. The optional lab in Step 9 then adds event topics, a many-to-many field, in a disposable copy.

The Custom Way

This illustration reads related rows by hand from two small tables in memory, the way hand-written database code often did; do not add it to the project. set_trace_callback() is a sqlite3 feature that calls a function with each SQL statement the connection runs, so the list sent counts the queries:

import sqlite3

db = sqlite3.connect(':memory:')
db.executescript('''
    CREATE TABLE event (id INTEGER PRIMARY KEY, title TEXT);
    CREATE TABLE registration (
        id INTEGER PRIMARY KEY,
        event_id INTEGER NOT NULL REFERENCES event (id),
        member TEXT NOT NULL
    );
    INSERT INTO event VALUES (1, 'Python meetup'),
                             (2, 'Django workshop');
    INSERT INTO registration (event_id, member)
    VALUES (1, 'Sai'), (1, 'Raj'), (2, 'Sai');
''')
sent = []
db.set_trace_callback(sent.append)

listed = 'SELECT event_id, member FROM registration'
for event_id, member in db.execute(listed).fetchall():
    (title,) = db.execute(
        'SELECT title FROM event WHERE id = ?', (event_id,)
    ).fetchone()
    print(member, title)
print('queries:', len(sent))

sent.clear()
joined = '''
    SELECT registration.member, event.title
    FROM registration
    JOIN event ON event.id = registration.event_id
'''
for member, title in db.execute(joined):
    print(member, title)
print('queries:', len(sent))
Sai Python meetup
Raj Python meetup
Sai Django workshop
queries: 4
Sai Python meetup
Raj Python meetup
Sai Django workshop
queries: 1

The first loop is the N+1 pattern, written out: one query for the registrations, then one for each row’s event. The JOIN asks once, and the database matches every registration to its event. Both print the same lines. Now list what the hand-written version still lacks: each row is a tuple to unpack by position, nothing turns event_id into an event object, the reverse question, “which registrations does this event have?”, needs another query written by hand, and nothing decides what happens when an event is deleted. Relationship fields give you all four.

The Django Way

Eight steps follow, and an optional ninth. Step 1 checks the start, Step 2 creates the app, Steps 3 to 5 write tests, models, and migrations, Steps 6 and 7 use the shell, and Step 8 commits. Step 9 is an optional lab, in a copy of the project, that builds a many-to-many field.

Step 1: Check the starting point

Run every test, beside manage.py, in PowerShell, Git Bash, a macOS shell, or Linux/WSL Bash:

uv run python manage.py test

Expected result, shortened with ...:

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'...

Then start the shell, in any of the four shells:

uv run python manage.py shell

Count the events and the members:

13 objects imported automatically (use -v 2 for details).

Python 3.14.9 ...
Type "help", "copyright", "credits" or "license" for ...
(InteractiveConsole)
>>> Event.objects.count()
3
>>> User.objects.count()
1
>>> User.objects.get().display_name
'Sam'
>>> exit()
now exiting InteractiveConsole...

Three events from Chapter 19, and one member: the superuser you created in Chapter 18, sam@example.org, whose display name is Sam. get() with no conditions returns the only row, and would raise an error if there were none or several. Sam becomes the meetup’s organizer in Step 6.

If your counts differ, rows are left from experiments of your own. Keep them; the chapter works with any events. If User.objects.get() raises MultipleObjectsReturned, you have more than one member: Step 6 fetches Sam by his email address, so that is fine too. If it raises DoesNotExist, Chapter 18’s superuser is missing; create it with Chapter 18’s createsuperuser step, using sam@example.org and the display name Sam.

Step 2: Create the registrations app

Create the app with Chapter 7’s command, beside manage.py, in any of the four shells:

uv run python manage.py startapp registrations

The command prints nothing when it succeeds. It creates a folder beside events: Give the generated apps.py its two docstrings, as Chapter 7 did for events/apps.py:

"""Configuration Django reads to load the registrations app."""
from django.apps import AppConfig


class RegistrationsConfig(AppConfig):
    """The registrations app: members' places at events."""

    name = 'registrations'
registrations/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

These are the files Chapter 7’s Table 7.4 described for events. apps.py holds the app’s configuration class, RegistrationsConfig, with name = 'registrations'. admin.py and views.py stay as they are until Chapters 23 and 31.

Common Error: the name is already taken

If startapp stops with CommandError saying that the name conflicts with an existing Python module, a folder or package called registrations already exists, perhaps from an earlier attempt. Nothing new was created. Look inside the existing folder rather than running the command again.

An app is part of the project only when INSTALLED_APPS names it. Open config/settings.py and add one line at the end of the list, after the events entry:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts.apps.AccountsConfig',
    'events.apps.EventsConfig',
    'registrations.apps.RegistrationsConfig',
]

Check the project:

uv run python manage.py check
System check identified no issues (0 silenced).

Step 3: Write the tests first

The tests describe what both models must do before either exists. Replace the contents of registrations/tests.py, which holds only an import and a comment, with this:

"""Tests for the registrations app."""
from datetime import UTC, datetime

from django.contrib.auth import get_user_model
from django.db.models import ProtectedError
from django.test import TestCase

from events.models import Event
from .models import Registration

User = get_user_model()


class RegistrationTests(TestCase):
    """A registration links a member to an event."""

    @classmethod
    def setUpTestData(cls):
        cls.event = Event.objects.create(
            title='Python meetup',
            starts_at=datetime(2026, 11, 19, 18, 30,
                               tzinfo=UTC),
            ends_at=datetime(2026, 11, 19, 20, 30,
                             tzinfo=UTC),
            timezone='Europe/London',
            location='Leeds Central Library',
            capacity=40,
        )
        cls.member = User.objects.create_user(
            'sai@example.org', display_name='Sai'
        )
        cls.registration = Registration.objects.create(
            event=cls.event, member=cls.member
        )

    def test_registration_links_event_and_member(self):
        registration = self.registration
        self.assertEqual(registration.event, self.event)
        self.assertEqual(registration.member, self.member)
        self.assertEqual(
            registration.status, Registration.Status.ACTIVE
        )
        self.assertQuerySetEqual(
            self.event.registrations.all(), [registration]
        )
        self.assertQuerySetEqual(
            self.member.registrations.all(), [registration]
        )

    def test_event_with_registration_is_kept(self):
        with self.assertRaises(ProtectedError):
            self.event.delete()
        self.assertTrue(
            Event.objects.filter(pk=self.event.pk).exists()
        )

    def test_member_with_registration_is_kept(self):
        with self.assertRaises(ProtectedError):
            self.member.delete()
        self.assertTrue(
            User.objects.filter(pk=self.member.pk).exists()
        )

get_user_model() returns the user class, as the Prefer callout advised for code like this. create_user() without a password gives Sai an account that cannot sign in yet, which is all a test needs. The first test checks both directions: the registration’s event and member, its default status, and the two reverse managers, event.registrations and member.registrations. assertQuerySetEqual() compares a QuerySet with a list, in order. The other two tests try to delete the event and the member, expect ProtectedError, and then check that each row is still there, so that a refused delete cannot pass by deleting something anyway.

Now the organizer assignment’s tests, in events/tests.py. At the top of the file, three lines change: two imports are added, and the models import names OrganizerAssignment too. The import block becomes:

from datetime import UTC, datetime, timedelta
from pathlib import Path

from django.contrib.auth import get_user_model
from django.contrib.staticfiles import finders
from django.core.exceptions import ValidationError
from django.db.models import ProtectedError
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, OrganizerAssignment

User = get_user_model()

Then add a class at the end of the file, after EventModelTests:

class OrganizerAssignmentTests(TestCase):
    """An assignment links an organizer to an event."""

    @classmethod
    def setUpTestData(cls):
        cls.event = save_event()
        cls.member = User.objects.create_user(
            'sam@example.org', display_name='Sam'
        )
        cls.assignment = OrganizerAssignment.objects.create(
            event=cls.event, member=cls.member
        )

    def test_assignment_links_event_and_member(self):
        assignment = self.assignment
        self.assertEqual(assignment.event, self.event)
        self.assertEqual(assignment.member, self.member)
        self.assertIsNone(assignment.revoked_at)
        self.assertQuerySetEqual(
            self.event.organizer_assignments.all(),
            [assignment],
        )
        self.assertQuerySetEqual(
            self.member.organizer_assignments.all(),
            [assignment],
        )

    def test_assigned_event_and_member_are_kept(self):
        for row in (self.event, self.member):
            model = type(row)
            with self.subTest(model=model.__name__):
                with self.assertRaises(ProtectedError):
                    row.delete()
                kept = model.objects.filter(pk=row.pk)
                self.assertTrue(kept.exists())

    def test_unlinked_event_can_be_deleted(self):
        spare = save_event(title='Spare event')
        self.assertEqual(
            spare.delete(), (1, {'events.Event': 1})
        )

save_event() is Chapter 19’s helper, near the top of the same file. The test database is separate from yours, so sam@example.org here is a new, test-only member. In this class, the event and the member are linked only by the assignment, with no registration. That matters: if the event also had a registration, the registration’s PROTECT would refuse the delete on its own, and a wrong rule on the assignment would go unnoticed. type(row) is the row’s model, Event or User, so one loop checks both. The last test proves that the rule is “keep what history needs”, not “never delete”: an event that nothing points at can still be deleted, and delete() reports one Event.

Run every test:

uv run python manage.py test

Expected result, shortened with ...:

Found 11 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
EE.........
...
ERROR: events.tests (unittest.loader._FailedTest.events...
...
ImportError: cannot import name 'OrganizerAssignment' fr...
...
ERROR: registrations.tests (unittest.loader._FailedTest...
...
ImportError: cannot import name 'Registration' from 'reg...
...
FAILED (errors=2)
Destroying test database for alias 'default'...

Only 11 tests were found, not 36. When a test module cannot be imported, Python’s test loader replaces the whole module with one failing placeholder, so each of the two modules counts as one error, and none of the events tests ran. The nine tests that did run are Chapter 17’s and Chapter 18’s, in accounts and config. This red stage is expected: both models are missing.

Step 4: Write the two models

Replace the contents of registrations/models.py with this:

"""Members' places at Otahque's events."""
from django.conf import settings
from django.db import models
from django.utils import timezone


class Registration(models.Model):
    """A member's place in an event, from the ERD."""

    class Status(models.TextChoices):
        """Whether the place is held: active or cancelled."""

        ACTIVE = 'active', 'Active'
        CANCELLED = 'cancelled', 'Cancelled'

    event = models.ForeignKey(
        'events.Event',
        on_delete=models.PROTECT,
        related_name='registrations',
    )
    member = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        related_name='registrations',
    )
    status = models.CharField(
        max_length=20,
        choices=Status,
        default=Status.ACTIVE,
    )
    registered_at = models.DateTimeField(
        default=timezone.now
    )
    cancelled_at = models.DateTimeField(
        null=True, blank=True
    )

    class Meta:
        ordering = ['registered_at']

    def __str__(self):
        return f'{self.member} at {self.event}'

Each part comes from the ERD or from an earlier chapter. The two foreign keys name their targets three ways you now know: 'events.Event' as a string, and the user model through the setting. related_name='registrations' on both is not a clash, because the names live on different models: Event gets registrations, and so does User. Status is a TextChoices class like the event’s, with active as the default. registered_at uses default=timezone.now, as Chapter 17’s date_joined does: the function itself, without brackets, so Django calls it for each new row. auto_now_add=True would also fill it, but would make the field impossible to set, which Chapter 41 needs when it imports registrations with their original times. cancelled_at may be empty, in Python as None and in the database as NULL, because a registration that has not been cancelled has no cancellation time; blank=True tells forms, from Chapter 24, that it is optional. Registrations are listed in the order they were made, and __str__() describes one for the shell and error messages.

Now open events/models.py. Replace its first line, from django.db import models, with three imports:

from django.conf import settings
from django.db import models
from django.utils import timezone

Then add a class at the end of the file, after Event:

class OrganizerAssignment(models.Model):
    """Which member organizes which event, from the ERD."""

    event = models.ForeignKey(
        Event,
        on_delete=models.PROTECT,
        related_name='organizer_assignments',
    )
    member = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        related_name='organizer_assignments',
    )
    assigned_at = models.DateTimeField(
        default=timezone.now
    )
    revoked_at = models.DateTimeField(
        null=True, blank=True
    )

    class Meta:
        ordering = ['assigned_at']

    def __str__(self):
        return f'{self.member} organizes {self.event}'

Event is named directly, because it is defined above in the same file. An assignment is current while revoked_at is empty; revoking one fills it in and keeps the row, the same idea as a cancelled registration. Who may assign and revoke organizers is Chapter 30’s question. Check the project:

uv run python manage.py check
System check identified no issues (0 silenced).

Common Error: two reverse names that clash

If OrganizerAssignment.member also had related_name='registrations', User would be given two attributes with one name. check refuses with four messages, two for each field. The first begins events.OrganizerAssignment.member: (fields.E304) Reverse accessor 'User.registrations' for 'events.OrganizerAssignment.member' clashes with reverse accessor for 'registrations.Registration.member'. The others, fields.E305, say the same of the names used in lookups. Give each relationship to the same model its own related_name, as in the listings.

Two smaller mistakes stop the project before check can report anything. A foreign key without on_delete fails with TypeError: ForeignKey.__init__() missing 1 required positional argument: 'on_delete'. A model file that uses settings without importing it fails with NameError: name 'settings' is not defined. A misspelled string, such as 'event.Event', gives two check errors, fields.E300 and fields.E307, the second saying that app 'event' isn't installed. In each case, compare the file with the listing.

Run the tests now, before creating any migration:

uv run python manage.py test

Expected result, shortened with ...:

Found 36 test(s).
...
FAIL: test_every_model_change_has_a_migration ...
...
AssertionError: Missing migrations:
...
FAILED (failures=1, errors=3)
...

All 36 tests are found now, because both modules import. Most pass, but the test database is built from migrations, and no migration creates the two new tables yet, so the tests that touch them stop with errors. Chapter 18’s test_every_model_change_has_a_migration names the cause: models have changed without a migration. That test exists for exactly this moment.

Step 5: Create and apply the migrations

Ask Django for the migrations, for every app at once:

uv run python manage.py makemigrations
Migrations for 'events':
  events\migrations\0002_organizerassignment.py
    + Create model OrganizerAssignment
Migrations for 'registrations':
  registrations\migrations\0001_initial.py
    + Create model Registration

On macOS and Linux, the paths use / instead of \. Each app gets its own migration: the events app’s second, and the registrations app’s first. Open registrations/migrations/0001_initial.py. Near the top, it lists what must be applied before it:

    dependencies = [
        ('events', '0002_organizerassignment'),
        migrations.swappable_dependency(settings...
    ]

The last line is shortened here; in the file it ends settings.AUTH_USER_MODEL),. A registration points at an event and a member, so their tables must exist first. Django wrote the dependency on the events app’s newest migration, which exists because both were made in one run, and a swappable dependency on whichever app holds AUTH_USER_MODEL. Like every migration in this book, the file stays exactly as makemigrations wrote it.

Common Error: an app that is not installed

If Step 2’s settings line is missing, makemigrations creates only the events migration, and makemigrations registrations stops with No installed app with label 'registrations'. The tests stop too, with RuntimeError: Model class registrations.models.Registration doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Add the line to INSTALLED_APPS and run the command again; nothing needs deleting.

Read the SQL the registrations migration will run:

uv run python manage.py sqlmigrate registrations 0001

Expected result, with long lines shortened:

BEGIN;
--
-- Create model Registration
--
CREATE TABLE "registrations_registration" ("id" integer...
CREATE INDEX "registrations_registration_event_id_3b9749...
CREATE INDEX "registrations_registration_member_id_fd206...
COMMIT;

On your screen, the CREATE TABLE line ends with the two foreign keys: "event_id" bigint NOT NULL REFERENCES "events_event" ("id") DEFERRABLE INITIALLY DEFERRED, and the same for "member_id" and "accounts_user". The two CREATE INDEX lines are the indexes Django adds to every foreign key. There is no ON DELETE clause: PROTECT lives in Python, in the deletion collector. Run sqlmigrate events 0002 too, and you see the same shape for events_organizerassignment.

Apply both migrations:

uv run python manage.py migrate
Operations to perform:
  Apply all migrations: accounts, admin, auth, ...
Running migrations:
  Applying events.0002_organizerassignment... OK
  Applying registrations.0001_initial... OK

The events migration runs first, because the registrations migration depends on it. Run every test:

uv run python manage.py test

Expected result, shortened with ...:

Found 36 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
....................................
...
Ran 36 tests in ...

OK
Destroying test database for alias 'default'...

Thirty tests from before, three for registrations, and three for organizer assignments, all passing.

Step 6: Connect rows in the shell

Start the shell with uv run python manage.py shell. Its first line now says 15 objects imported automatically: Registration and OrganizerAssignment are imported for you too. Fetch Sam, and create Sai and Raj as members:

>>> sam = User.objects.get(email='sam@example.org')
>>> sai = User.objects.create_user(
...     'sai@example.org', display_name='Sai'
... )
>>> raj = User.objects.create_user(
...     'raj@example.org', display_name='Raj'
... )
>>> User.objects.count()
3
>>> sai.has_usable_password()
False

Sam already exists, so he is fetched, never created again; making him an organizer needs an assignment row, not a second account. Sai and Raj are created without passwords. create_user() then marks the password as unusable, so neither can sign in until Chapter 27 builds sign-up, and no password is typed into the shell. The addresses use example.org, a domain reserved for examples, like Sam’s.

Now make Sam the meetup’s organizer, and register Sai:

>>> meetup = Event.objects.get(title='Python meetup')
>>> workshop = Event.objects.get(title='Django workshop')
>>> assignment = OrganizerAssignment.objects.create(
...     event=meetup, member=sam
... )
>>> print(assignment)
sam@example.org organizes Python meetup
>>> booking = Registration.objects.create(
...     event=meetup, member=sai
... )
>>> booking
<Registration: sai@example.org at Python meetup>
>>> booking.event_id, booking.member_id
(1, 2)
>>> print(booking.status)
active
>>> booking.event.location
'Leeds Central Library, Room 2'

create() accepts objects for the foreign keys, and Django stores their ids. booking.event_id and booking.member_id are those ids, read without a query; your numbers may differ if your event or Sam has a different id. booking.event is the event itself, so booking.event.location reads its location. Sam is staff, but that is not what makes him an organizer: the assignment row is, as Chapter 17 argued.

Register Raj for the meetup and Sai for the workshop, then look from the other side:

>>> Registration.objects.create(event=meetup, member=raj)
<Registration: raj@example.org at Python meetup>
>>> Registration.objects.create(event=workshop, member=sai)
<Registration: sai@example.org at Django workshop>
>>> for booking in meetup.registrations.all():
...     print(booking.member.display_name, booking.status)
...
Sai active
Raj active
>>> sai.registrations.count()
2
>>> for assignment in sam.organizer_assignments.all():
...     print(assignment.event)
...
Python meetup

meetup.registrations is the related manager from What You Need to Know: all() returns the meetup’s registrations, in the model’s order, and count() asks the database how many Sai has. Two mistakes with it are common. Try both:

>>> meetup.registration_set
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Event' object has no attribute ...
>>> for booking in meetup.registrations:
...     print(booking)
...
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'RelatedManager' object is not iterable

The first is the default name, which related_name replaced; the full message ends Did you mean: 'registrations'?. The second loops over the manager itself. A manager is where queries start, not a list of rows, so add .all(), as in the earlier loop.

Filter across relationships with the double underscore, in both directions:

>>> Event.objects.filter(registrations__member=sai)
<QuerySet [<Event: Python meetup>, <Event: Django workshop>]>
>>> online = Registration.objects.filter(
...     event__location='Virtual'
... )
>>> [booking.member.display_name for booking in online]
['Sai']
>>> User.objects.filter(organizer_assignments__event=meetup)
<QuerySet [<User: sam@example.org>]>

The first goes backwards, from events to their registrations, and finds both of Sai’s events. The second goes forwards, from registrations to their event’s location. The third asks which members organize the meetup. Now the repeated-row surprise:

>>> active = Event.objects.filter(
...     registrations__status=Registration.Status.ACTIVE
... )
>>> [event.title for event in active]
['Python meetup', 'Python meetup', 'Django workshop']
>>> [event.title for event in active.distinct()]
['Python meetup', 'Django workshop']

The meetup has two active registrations, so the join produces two meetup rows. distinct() asks the database for each event once. Use it whenever a filter across a reverse relationship could match several rows for one result.

Finally, try to delete the meetup:

>>> meetup.delete()
Traceback (most recent call last):
...
django.db.models.deletion.ProtectedError: ("Cannot delete ...
>>> Event.objects.filter(pk=meetup.pk).exists()
True

The full message is long: Cannot delete some instances of model 'Event' because they are referenced through protected foreign keys: 'OrganizerAssignment.event', 'Registration.event'., followed by the rows that refer to the meetup. The traceback passes through Django’s deletion.py, the collector from Figure 20.1. The meetup is still there, and so is everything that points at it. Leave the shell with exit().

Step 7: Count the queries

Start the shell again. Loop over every registration, print each member’s name and event, and count the queries:

>>> from django.test.utils import CaptureQueriesContext
>>> with CaptureQueriesContext(connection) as queries:
...     for booking in Registration.objects.all():
...         print(booking.member.display_name, booking.event)
...     print('queries:', len(queries))
...
Sai Python meetup
Raj Python meetup
Sai Django workshop
queries: 7

Seven: one for the registrations, then a member and an event for each of the three, the left side of Figure 20.3. Now ask for the related rows in the same query:

>>> joined = Registration.objects.select_related(
...     'event', 'member'
... )
>>> with CaptureQueriesContext(connection) as queries:
...     for booking in joined:
...         print(booking.member.display_name, booking.event)
...     print('queries:', len(queries))
...
Sai Python meetup
Raj Python meetup
Sai Django workshop
queries: 1
>>> str(joined.query).count('INNER JOIN')
2

The same lines, from one query. str(joined.query) is the approximate SQL from Chapter 19, and it holds two INNER JOINs, one for each related table. From the other direction, events with their registrations, use prefetch_related():

>>> with_bookings = Event.objects.prefetch_related(
...     'registrations'
... )
>>> with CaptureQueriesContext(connection) as queries:
...     for event in with_bookings:
...         print(event, len(event.registrations.all()))
...     print('queries:', len(queries))
...
Python meetup 2
Django workshop 1
Spring planning 0
queries: 2

Two queries: one for the events, and one for all their registrations together, which Django shares out among the events. Without prefetch_related(), the loop would run one more query for each event. Leave the shell with exit(). Nothing in this step changed a row.

Step 8: Review and commit

Look at what changed:

git status --short
 M config/settings.py
 M events/models.py
 M events/tests.py
?? events/migrations/0002_organizerassignment.py
?? registrations/

Three changed files and two new paths: the events migration, and the whole registrations folder, which Git lists as one line until it is added. db.sqlite3 is not listed, because Git ignores it, so Sai, Raj, and their registrations stay on your computer. Commit:

git add config events registrations
git commit -m "Add registrations and organizer assignments"

git status --short then prints nothing.

Step 9: Optional lab: event topics, a many-to-many field

This step is an experiment, like Chapter 18’s slug lab. Otahque’s first release has no topics, as Chapter 15’s ERD records, so you build them in a copy of the project and discard the copy afterwards. The lab exists for one reason: it is the place where you write a ManyToManyField yourself and watch the link table Django creates for it. Run every command in this step inside the lab folder, never in your project. If you skip it, nothing later in the main path depends on it; Chapters 55 and 56 return to topics in an optional lab of their own.

From the folder that holds manage.py, clone the project you committed in Step 8 into the practice folder, in any of the four shells:

git clone . ../practice/relations-lab

Copy your .env into the lab. In PowerShell:

Copy-Item .env ..\practice\relations-lab\.env

In Git Bash, a macOS shell, or Linux/WSL Bash:

cp .env ../practice/relations-lab/.env

Then move into the lab, build its environment, create its tables, and add three events with Chapter 18’s helper, add_lab_events.py, which is still in the practice folder:

cd ../practice/relations-lab
uv sync --locked
uv run python manage.py migrate
uv run python ../add_lab_events.py

The last command prints 3 events. If you no longer have the helper, recreate it from Chapter 18, Step 7.

In the lab’s events/models.py, add a field to Event, directly after status:

    topics = models.ManyToManyField(
        'Topic', blank=True, related_name='events'
    )

Then add a model at the end of the file:

class Topic(models.Model):
    """A subject an event covers; lab only."""

    name = models.CharField(max_length=50, unique=True)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name

'Topic' is a string because the class is defined further down the file, the same lazy reference you used for 'events.Event'. blank=True lets an event have no topics; a many-to-many field never needs null=True, because it adds no column to the event table. related_name='events' names the reverse side, so a topic lists its events with python.events. There is no on_delete: you will see why at the end of the lab.

Run Chapter 18’s guard test before writing the migration:

uv run python manage.py test config

Expected result, shortened with ...:

Found 1 test(s).
...
AssertionError: Missing migrations:
Migrations for 'events':
  events\migrations\0003_topic_event_topics.py
    + Create model Topic
    + Add field topics to event
...
FAILED (failures=1)

That is the red stage: the model changed and no migration describes it. Write the migration and read its SQL:

uv run python manage.py makemigrations
uv run python manage.py sqlmigrate events 0003

The first command names the same file and its two operations. The second prints this, with long lines shortened:

BEGIN;
...
CREATE TABLE "events_topic" ("id" integer NOT NULL PRIM...
...
CREATE TABLE "events_event_topics" ("id" integer NOT NU...
CREATE UNIQUE INDEX "events_event_topics_event_id_topic...
CREATE INDEX "events_event_topics_event_id_899728de" ...
CREATE INDEX "events_event_topics_topic_id_1e1f2630" ...
COMMIT;

The field you wrote on Event became a whole table, events_event_topics, with its own id, an event_id, and a topic_id: the third table from Table 20.1. Its unique index on the pair means that one event cannot hold the same topic twice. Apply it with uv run python manage.py migrate events, which prints Applying events.0003_topic_event_topics... OK.

Now use it. Start the shell with uv run python manage.py shell; its first line says 16 objects imported automatically, because Topic is imported too. Attach topics to two events, then read them from both sides:

>>> meetup = Event.objects.first()
>>> sprint = Event.objects.get(title='Django sprint')
>>> python = Topic.objects.create(name='Python')
>>> web = Topic.objects.create(name='Web')
>>> meetup.topics.add(python)
>>> sprint.topics.add(python, web)
>>> sprint.topics.add(web)
>>> sprint.topics.all()
<QuerySet [<Topic: Python>, <Topic: Web>]>
>>> python.events.all()
<QuerySet [<Event: Python meetup>, <Event: Django sprint>]>

add() writes rows into the link table, one for each pair, and adding web a second time changes nothing, because the pair is already there. meetup.topics and python.events are related managers, like meetup.registrations, but here both sides are plural. Filters cross the link table with the double underscore, and repeat rows as reverse filters did in Step 6:

>>> both = Event.objects.filter(
...     topics__name__in=['Python', 'Web']
... )
>>> [event.title for event in both]
['Python meetup', 'Django sprint', 'Django sprint']
>>> [event.title for event in both.distinct()]
['Python meetup', 'Django sprint']
>>> Event.topics.through
<class 'events.models.Event_topics'>
>>> Event.topics.through.objects.count()
3

The sprint matches both topics, so it appears twice until distinct(). through is the model Django made for the link table; it has no fields of its own beyond the two keys, which is exactly why a registration, with its status and times, could not be one. Reading each event’s topics in a loop is a query per row again, and prefetch_related() fixes it, as in Step 7:

>>> from django.test.utils import CaptureQueriesContext
>>> with CaptureQueriesContext(connection) as queries:
...     events = Event.objects.prefetch_related('topics')
...     for e in events:
...         print(e, [t.name for t in e.topics.all()])
...     print('queries:', len(queries))
...
Python meetup ['Python']
Django sprint ['Python', 'Web']
Python meetup []
queries: 2

Without prefetch_related(), the same loop runs four queries: one for the events and one for each event’s topics. Finally, remove a link and delete a topic:

>>> sprint.topics.remove(web)
>>> web.events.all()
<QuerySet []>
>>> python.delete()
(3, {'events.Event_topics': 2, 'events.Topic': 1})
>>> meetup.topics.all()
<QuerySet []>

remove() deletes one link row and leaves both the event and the topic. Deleting the Python topic deleted it and its two link rows, and the events are untouched. That answers the on_delete question: the link table Django makes always cascades, because a link row means nothing without both ends, and you cannot choose otherwise. When a link needs a rule of its own, or facts of its own, it becomes a model with two foreign keys, as Registration is. Leave the shell with exit().

Run the lab backwards, to the migration before topics, and check what is left:

uv run python manage.py migrate events 0002
uv run python manage.py showmigrations events
...
  Unapplying events.0003_topic_event_topics... OK
events
 [X] 0001_initial
 [X] 0002_organizerassignment
 [ ] 0003_topic_event_topics

Both new tables are gone, and the three events remain. When you have finished, delete the relations-lab folder inside the practice folder; your project never saw any of it, and its 36 tests and commit are unchanged.

When something goes wrong

Table 20.3 — Relationship problems and safe recovery
Symptom Likely cause Safe recovery
CommandError: conflicts with the name of an existing module A registrations folder already exists Inspect it; do not run startapp again
Found 11 test(s), FAILED (errors=2) The models do not exist yet Expected in Step 3; write Step 4's models
No installed app with label 'registrations' INSTALLED_APPS lacks the app Add Step 2's line; run the command again
missing 1 required positional argument: 'on_delete' A ForeignKey without on_delete Add on_delete=models.PROTECT
fields.E304 or fields.E305: clashes Two relations to one model share a name Give each its own related_name
fields.E300 and E307: app isn't installed A misspelled model string Use 'events.Event'
Missing migrations, with errors Tests ran before makemigrations Run makemigrations, then migrate
'Event' object has no attribute 'registration_set' The default name was replaced Use the related_name: registrations
'RelatedManager' object is not iterable A loop over the manager itself Add .all()
The same event twice in a result A filter across a reverse relation Add distinct()
ProtectedError when deleting PROTECT keeps history Intended; cancel or keep the row instead
Many queries in one loop Related rows loaded one at a time select_related() or prefetch_related()
Lab: IntegrityError: UNIQUE constraint failed: events_topic.name A topic with that name exists Fetch it with get() instead of creating it
Lab command run in the project Wrong folder git status, then git restore only the lab's files
PAGE 003

Verify Your Work

Work through Table 20.4 from the folder that holds manage.py. The test rows come first: they hold the deletion rules and the reverse names in place, whatever rows your database holds.

Table 20.4 — Verification checklist for Chapter 20
Check Command or action Expected result
Red stage seen The Step 3 run, before the models Found 11 test(s); FAILED (errors=2)
Tests pass uv run python manage.py test Found 36 test(s); OK
App installed INSTALLED_APPS in config/settings.py Ends with RegistrationsConfig
Migrations applied uv run python manage.py showmigrations events registrations [X] 0002_organizerassignment and [X] 0001_initial
Keys in the SQL sqlmigrate registrations 0001 REFERENCES lines and two CREATE INDEX lines
History kept meetup.delete() in the shell ProtectedError; the meetup still exists
One query The select_related() loop of Step 7 queries: 1
Committed git status --short No output
Optional lab migrate events 0002 in the lab [ ] 0003_topic_event_topics; three events kept
Not verified macOS, Linux, WSL; PostgreSQL Readers on those systems; Chapter 32

The query count has no test of its own yet, because no page reads related rows: the public pages are unchanged. When Chapter 31’s pages list registrations, their tests pin the count, as Chapter 19’s list test does. 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.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 2 A registration belongs to one event, and an event has many registrations. On which table is the foreign key, and what is its column called?

Flip to check your answerFold answer back

Answer. On the registration table, the many side: registrations_registration. The field is named event, so its column is event_id, holding the event’s primary key. The event table has no column for its registrations; meetup.registrations asks the registration table.

Que. 3 What is meetup.registrations, and why does for booking in meetup.registrations: fail?

Flip to check your answerFold answer back

Answer. It is a related manager: a manager limited to the meetup’s registrations, named by related_name. A manager starts queries but is not a list of rows, so looping over it raises TypeError: 'RelatedManager' object is not iterable. meetup.registrations.all() returns a QuerySet you can loop over.

Que. 4 Event.objects.filter(registrations__status='active') returned the meetup twice. Why, and what fixes it?

Flip to check your answerFold answer back

Answer. The filter joins each event to its registrations, and the meetup has two active ones, so the join yields two meetup rows. distinct() returns each event once.

Que. 5 What does PROTECT cost Otahque, and why is it still the right rule for registrations?

Flip to check your answerFold answer back

Answer. An event or a member that registrations point at cannot be deleted, so closing a member’s account needs a deliberate design, in Chapters 27 and 65. It is still right because registrations are records that the product’s rules and the ERD keep: CASCADE would erase them silently whenever someone deleted a parent row.

Mini-Challenge

Que. 6 Sam asks: “Which events does Sai have an active registration for, each listed once, 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, two conditions across the same relationship, and distinct(). Here is one session that answers it:

>>> from django.test.utils import CaptureQueriesContext
>>> sai = User.objects.get(email='sai@example.org')
>>> mine = Event.objects.filter(
...     registrations__member=sai,
...     registrations__status=Registration.Status.ACTIVE,
... ).distinct()
>>> with CaptureQueriesContext(connection) as queries:
...     print([event.title for event in mine])
...
['Python meetup', 'Django workshop']
>>> len(queries)
1

Both conditions are in one filter() call, so they must hold for the same registration: an active registration that is Sai’s. Django’s documentation points out that two separate filter() calls across a many-valued relationship could match two different registrations instead. distinct() guards against an event appearing twice; until Chapter 21’s constraint, nothing stops two active registrations for the same member and event. The model’s ordering lists the events soonest first, and the list comprehension runs exactly one query. An answer that starts from sai.registrations and reads each registration’s event also works, but runs a query per row unless it uses select_related('event').

What We Learned

  • A ForeignKey is the many side of a one-to-many relationship: a column ending _id, a database constraint, and an index; OneToOneField adds uniqueness, and ManyToManyField uses a third table.
  • Relations to the user model use settings.AUTH_USER_MODEL; relations to another app’s model can use a string such as 'events.Event'.
  • on_delete states what a relationship means: PROTECT keeps history by refusing deletes, CASCADE deletes dependent rows, and Django 6.1’s DB_ rules hand the work to the database.
  • Forward access, booking.event, follows the key; reverse access, meetup.registrations, is a related manager named by related_name.
  • The double underscore follows relationships in filters, in both directions; reverse filters can repeat rows, and distinct() removes the repeats.
  • Reading a related object in a loop runs a query per row; select_related() joins forward relations into one query, and prefetch_related() fetches reverse ones in one more.
  • A new app is created with startapp, installed in INSTALLED_APPS, and gets its own migrations, which can depend on other apps’ migrations.

Key terms

Use Table 20.5 to explain this chapter’s ideas in your own words.

Table 20.5 — Key terms from Chapter 20
Term Meaning
Relationship field A model field whose value is another model's row.
ForeignKey A many-to-one relationship: a key column on the many side.
on_delete The rule for rows that point at a row being deleted.
ProtectedError The error PROTECT raises to refuse a delete.
Deletion collector Django's code that finds dependent rows and applies on_delete rules.
Related manager A manager limited to one object's related rows, such as meetup.registrations.
related_name The name of the reverse relation on the other model.
Lazy reference A model named by a string such as 'events.Event', resolved later.
Swappable dependency A migration dependency on whichever app holds AUTH_USER_MODEL.
N+1 One query for a list plus one more for each of its N rows.
select_related Fetches forward related rows in the same query with joins.
prefetch_related Fetches related rows for many objects in one extra query.

Readiness checkpoint: you are ready for Chapter 21 when all 36 tests pass, showmigrations shows both new migrations applied, the meetup cannot be deleted in the shell, the select_related() loop runs one query, and git status --short prints nothing. Notice what is still possible: nothing stops Sai from having two active registrations for the meetup, or a cancelled registration with no cancellation time. Explain, in a sentence, why a check in Python code alone would not be enough to stop the first. Chapter 21 answers it. Return to the relevant step if any result is missing.

Git Commit

Your Chapter 20 work was committed in Step 8. For the record, these were the commands, in any of the four shells, beside manage.py:

git add config events registrations
git status --short
M  config/settings.py
A  events/migrations/0002_organizerassignment.py
M  events/models.py
M  events/tests.py
A  registrations/__init__.py
A  registrations/admin.py
A  registrations/apps.py
A  registrations/migrations/0001_initial.py
A  registrations/migrations/__init__.py
A  registrations/models.py
A  registrations/tests.py
A  registrations/views.py
git commit -m "Add registrations and organizer assignments"

A marks a file added to Git for the first time. Your members and registrations are not in the commit: rows live in db.sqlite3, and Chapter 41 chooses how Otahque shares sample data between computers.

PAGE 005

Test Your Knowledge: Interview Questions

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 27, 57, and 65. 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 rows and leave them as they are.

L1 (Junior): What are ForeignKey, OneToOneField, and ManyToManyField, and where is the key stored for each?

What the interviewer is testing: Can you match a relationship described in words to a field, and say what it becomes in the database?

Flip to check your answerFold answer back

Perfect answer: All three connect one model’s rows to another’s. ForeignKey is many-to-one: many registrations belong to one event. It is declared on the many side and becomes a column such as event_id, holding the other row’s primary key, with a foreign-key constraint and an index. OneToOneField is a foreign key with a unique constraint, for at most one row on each side, such as a profile beside an account. ManyToManyField is many-to-many, such as members and groups; no column is added to either table, because Django creates a third table that holds one row per pair of keys. I choose by reading the relationship aloud, and when a link has facts of its own, such as a registration’s status, I make it a model with two foreign keys instead of a plain many-to-many field. Foreign keys and one-to-one fields also need an on_delete rule.

Table 20.6 — Relationship fields compared
Field Database shape Example
ForeignKey Key column on the many side Registration.event
OneToOneField Unique key column A profile per member
ManyToManyField A third table of key pairs User.groups

Behind the scenes:

ForeignKey      -> event_id column, constraint, index
OneToOneField   -> the same, plus UNIQUE
ManyToManyField -> a third table: (left_id, right_id)
link with facts -> a model with two ForeignKeys

Code proof: two fields from your project, asked what they are:

import setup_django
from django.contrib.auth import get_user_model

from registrations.models import Registration

User = get_user_model()
key = Registration._meta.get_field('event')
print(type(key).__name__, key.many_to_one, key.column)
groups = User._meta.get_field('groups')
print(type(groups).__name__, groups.many_to_many,
      groups.remote_field.through._meta.db_table)
ForeignKey True event_id
ManyToManyField True accounts_user_groups

_meta is Django’s documented description of a model. The registration’s event is a many-to-one field stored in the column event_id; the user’s groups, from Chapter 17’s PermissionsMixin, is many-to-many, stored in the table accounts_user_groups.

Common mistakes:

  • Putting the foreign key on the one side, such as a registration field on Event.
  • Using ManyToManyField for a link that needs its own status or times.
  • Forgetting that OneToOneField is unique, so a second profile for the same member is refused.

Follow-up the interviewer might ask:

  • “How would you add a status to an existing many-to-many link?”
  • “Why does ManyToManyField need no on_delete?”

L2 (Mid-Level): What does related_name do, and why can a filter across a reverse relationship return the same row twice?

What the interviewer is testing: Do you understand the reverse side of a relationship, in Python and in the SQL it produces?

Flip to check your answerFold answer back
Five numbered steps. related_name names the reverse manager. event.registrations lists one event’s rows. filter(registrations__...) joins the table. One event row per matching registration. distinct() keeps each event once.
Figure 20.4 — The reverse side of a relationship, in Python and in a filter.

Perfect answer: A foreign key is declared on one model, but Django adds the reverse direction to the other model. related_name names it. On an object it is a related manager: meetup.registrations.all() and .count() query only that event’s registrations. Without related_name the manager is called registration_set, and the name used in lookups is the lowercase model name. Two relations from different models to the same model need different names, or check reports fields.E304 and E305. In a filter, Event.objects.filter(registrations__status='active') becomes a JOIN from events to registrations with a WHERE on the registration’s status. The join produces one row per matching registration, so an event with two active registrations appears twice. distinct() asks the database to return each event once. Conditions in one filter() call must hold for the same related row; conditions in chained filter() calls may match different ones.

Behind the scenes:

related_name='registrations'
  meetup.registrations    -> manager, this event only
  filter(registrations__) -> JOIN registrations
two matches               -> the event twice
.distinct()               -> each event once

Code proof: Sai’s reverse manager, and the same filter counted with and without distinct():

import setup_django
from django.contrib.auth import get_user_model

from events.models import Event

User = get_user_model()
sai = User.objects.get(email='sai@example.org')
print(type(sai.registrations).__name__)
print(sai.registrations.count())
active = 'active'
matching = Event.objects.filter(registrations__status=active)
print(matching.count(), matching.distinct().count())
RelatedManager
2
3 2

Common mistakes:

  • Looping over meetup.registrations instead of meetup.registrations.all().
  • Giving two relations to the user model the same related_name.
  • Counting results of a reverse filter without distinct(), and reporting too many events.

Follow-up the interviewer might ask:

  • “When would you set related_name='+'?”
  • “What is the difference between filter(a, b) and filter(a).filter(b) across a many-valued relation?”

L3 (Senior): How do you choose an on_delete rule, and what is the difference between Django’s CASCADE and Django 6.1’s DB_CASCADE?

What the interviewer is testing: Can you treat a deletion rule as a statement about data, and do you know where the rule actually runs?

Flip to check your answerFold answer back
Five numbered steps. Ask what the row means without its parent. History must stay: PROTECT. Part of its parent: CASCADE. Many rows, no signals: DB_CASCADE. Test the rule with a refused delete.
Figure 20.5 — Choosing a deletion rule from what the data means.

Perfect answer: I ask what a dependent row means once its parent is gone. If it is history that the business needs, such as a registration or an organizer assignment, I use PROTECT, and accept that deleting the parent becomes a deliberate process, such as cancelling or anonymizing. If the row is part of its parent and meaningless alone, such as a line in a draft that is being discarded, CASCADE fits. If the link is optional, SET_NULL, with null=True. Where the rule runs matters too. CASCADE, PROTECT, and SET_NULL are applied in Python by Django’s deletion collector: it queries the dependent rows, sends pre_delete and post_delete signals for each, and deletes inside one transaction. DB_CASCADE, new in Django 6.1, writes ON DELETE CASCADE into the table, so the database deletes the rows itself: faster for many rows, but without loading them and without signals, so code that relies on those signals will not run. Whatever I choose, a test that tries the delete proves the rule.

Behind the scenes:

PROTECT    -> collector refuses: ProtectedError
CASCADE    -> collector deletes, sends signals
SET_NULL   -> collector empties the key
DB_CASCADE -> SQL ON DELETE CASCADE, no signals

Code proof: inside a transaction that is rolled back, a temporary member in a group is deleted, and the group link goes with them, because Django’s own link table uses CASCADE; then Sai’s delete is refused:

import setup_django
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.db import transaction
from django.db.models import ProtectedError

User = get_user_model()
with transaction.atomic():
    temp = User.objects.create_user(
        'temp@example.org', display_name='Temp'
    )
    temp.groups.add(Group.objects.create(name='Helpers'))
    print('CASCADE:', temp.delete())
    sai = User.objects.get(email='sai@example.org')
    try:
        sai.delete()
    except ProtectedError as error:
        print('PROTECT:', len(error.protected_objects),
              'registrations keep Sai')
    transaction.set_rollback(True)
print(User.objects.filter(email='sai@example.org').exists())
CASCADE: (2, {'accounts.User_groups': 1, 'accounts.User': 1})
PROTECT: 2 registrations keep Sai
True

delete() reported two rows: the member and the link row in accounts_user_groups. protected_objects holds the rows that refused Sai’s delete: her two registrations. The rollback undoes the temporary member and group.

Common mistakes:

  • Using CASCADE by habit for records that history needs.
  • Choosing SET_NULL without null=True, which check reports as fields.E320.
  • Switching to DB_CASCADE for speed when signal receivers clean up files or caches.

Follow-up the interviewer might ask:

  • “An event is cancelled. Should its registrations be deleted, cancelled, or left alone?”
  • “Where else can deletes bypass your Python rules?”

L4 (Staff): A page that lists registrations with member names and event titles runs 201 queries. How do you find the cause, fix it, and keep it fixed?

What the interviewer is testing: Looking ahead: can you diagnose N+1 with related objects, choose the right tool for each relationship, and stop it returning?

Flip to check your answerFold answer back
Five numbered steps. Count the page’s queries. 1 + N: one more per row. select_related() for foreign keys. prefetch_related() for reverse and many. Tests and FETCH_RAISE keep it fixed.
Figure 20.6 — Finding, fixing, and fencing an N+1.

Perfect answer: 201 for 100 rows is 1 + 2N: one query for the registrations, then one for each row’s member and one for its event, because each related object is loaded the first time the template reads it. I confirm it with assertNumQueries, CaptureQueriesContext, or a tool such as Django Debug Toolbar, and look for the repeated query. Both relations are forward foreign keys, so select_related('member', 'event') fetches them in the same query with joins, and the page runs one query. For reverse or many-to-many relations, such as each event’s registrations, prefetch_related() adds one query per relation instead of one per row. To keep it fixed, the page’s test asserts the query count with several rows, so N+1 cannot hide behind one row. Django 6.1 adds another fence: fetch_mode(FETCH_RAISE) makes any unplanned related fetch raise FieldFetchBlocked, so a missing select_related() fails in development instead of slowing production. In Otahque, Chapter 22 composes these queries into named methods, and Chapter 57 measures them and sets the project’s policy.

Behind the scenes:

1 query       -> the registrations
+2 per row    -> member and event, on first access
select_related('member', 'event') -> 1 query
FETCH_RAISE   -> unplanned fetch raises at once

Code proof: with FETCH_RAISE, the first related access stops the loop; with select_related(), the same loop runs:

import setup_django
from django.core.exceptions import FieldFetchBlocked
from django.db.models import FETCH_RAISE

from registrations.models import Registration

strict = Registration.objects.fetch_mode(FETCH_RAISE)
try:
    for booking in strict:
        print(booking.event.title)
except FieldFetchBlocked as error:
    print('blocked:', error)
for booking in strict.select_related('event'):
    print(booking.event.title)
blocked: Fetching of Registration.event blocked.
Python meetup
Python meetup
Django workshop

Common mistakes:

  • Using prefetch_related() for a forward foreign key, where a join needs no extra query.
  • Calling select_related() with no arguments, which follows every non-null foreign key; Django 6.1 deprecates that form and warns.
  • Testing the query count with one row, 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 list each event with only its active registrations, without N+1?”

L5 (Lead): A member asks to close their account, but PROTECT keeps their registrations. How do you design for privacy and history together?

What the interviewer is testing: Looking ahead: can you turn a database rule into a product and data-protection design, with owners and evidence?

Flip to check your answerFold answer back
Five numbered steps. A member asks to close their account. PROTECT keeps their registrations. Deactivate and remove personal details. Keep what history needs, for a stated time. Test closure, export, and retention.
Figure 20.7 — Closing an account without losing the history that others rely on.

Perfect answer: PROTECT did its job: it stopped a delete that would have broken history, and it moved the decision to the people who own the data. The design starts with a written policy, agreed with whoever is responsible for data protection: what Otahque must keep, such as registration counts for past events, what it must remove, such as the email address and display name, and for how long anything is kept. Closing an account then becomes a deliberate workflow rather than delete(): deactivate the account so it cannot sign in, cancel future registrations so places are released, and replace personal details with an anonymous placeholder, so that past registrations still count but no longer identify the member. A retention job, from Chapter 41’s management commands, removes what the policy says to remove when its time comes, and audit records, in Chapter 65, show who closed what and when. I would give the member a way to export their data first, and test each part: closure, export, released places, and the retention rule. Chapter 27 builds account workflows, and Chapter 65 audit and retention; the policy itself is a product decision, not something the database chooses.

Behind the scenes:

request -> deactivate, cancel future places
personal details -> replaced, anonymous
past registrations -> kept, counted
retention job -> removes data on schedule
evidence -> tests and audit records

Code proof: the registrations tests, including the one that refuses to delete a member with a registration. In PowerShell:

uv run python manage.py test -v 2 `
    registrations

In Git Bash, a macOS shell, or Linux/WSL Bash:

uv run python manage.py test -v 2 \
    registrations

Expected result, shortened with ...:

Found 3 test(s).
...
test_event_with_registration_is_kept (registrations.test...
test_member_with_registration_is_kept (registrations.tes...
test_registration_links_event_and_member (registrations...
...
Ran 3 tests in ...

OK
...

-v 2 names each test as it runs, and on your screen each line ends ok. test_member_with_registration_is_kept is the guard this design must respect: a closure workflow changes the member’s details, it never deletes the row that history points at.

Common mistakes:

  • Switching the rule to CASCADE to make a deletion request “work”, and erasing other people’s history.
  • Treating deactivation alone as closure, while personal details stay.
  • Deciding retention periods in code review instead of in a written, owned policy.

Follow-up the interviewer might ask:

  • “Which data would you keep for an event that has already happened, and why?”
  • “How would you prove to a member that their details were removed?”

Next: Chapter 21 makes the database itself enforce Otahque’s rules, starting with one active registration per member and event.

PAGE 006