ContentsClose contents
Pre-release
Chapter 15 · Relational databases and our first ERDCHAPTER 15

Complete six-part pre-release for review. The data model is a proposal; no database tables are created in this chapter.

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 FIFTEEN

Relational databases and our first ERD

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

Prerequisites: Chapters 2, 5, and 8 to 14, including the Chapter 14 project, its 18 passing tests, and its Git repository

What you’ll build: a proposed entity-relationship diagram for members, events, organizer assignments, and registrations, committed to the project, and a small in-memory SQLite lab that shows the database refusing records that break Otahque’s rules.

Why This Matters

Before Otahque, Sam kept registrations for the community’s meetups in a spreadsheet. Each row was one registration, and each row repeated everything: the event’s title, date, and venue, then the member’s name and email address. When Sai changed her email address, Sam updated two of her three rows and missed the third, so his list now showed two people called Sai, and Sai could not tell which one held her confirmed place. When Raj cancelled, Sam deleted his row to free the place. A week later Raj asked whether his cancellation had gone through, and the spreadsheet had nothing left to say: a deleted row looks exactly like a registration that never happened. Counting the free places meant counting rows by eye. These are the conflicting answers Chapter 2 set out to remove.

So far, Otahque has avoided the problem by not storing anything. The event pages from Chapters 9 to 14 read a short list of fictional sample events written in Python, which disappears and reappears unchanged each time the server restarts. Registration needs records that last, that many people read and change, and that cannot contradict each other. A relational database provides them. It keeps each kind of thing in its own table, records each fact once, and links tables through identifying values called keys. It can also refuse a record that breaks a rule, such as a registration for an event that does not exist, whichever part of the program tried to save it.

Before Chapter 16 turns any of this into Django code, we design it. An entity-relationship diagram, or ERD, is a drawing of the kinds of things a system stores, the values that identify each one, and how they relate. It joins the documents you have already met: the BRD and PRD in Chapter 2 say what Otahque must do and why, and the ADR and HLD in Chapter 5 record a decision and the system’s main parts. The ERD says which records must exist for those rules to hold. A diagram is cheap to change; once a database holds real people’s registrations, every change has to carry their data along with it, which is what Chapter 18 is about.

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

  • explain why a relational database stores each fact once, in tables linked by keys;
  • find the entities, attributes, primary keys, and foreign keys in Otahque’s requirements;
  • read and draw relationships in crow’s foot notation, including how many records may take part and whether any must;
  • model a registration as a record of its own, with a status, so that each member holds at most one active place in an event and cancelled places stay in the history;
  • use Python’s built-in sqlite3 module with a throwaway in-memory database to watch the database refuse records that break these rules;
  • record a proposed ERD in the project, and trace each Chapter 2 rule to the structure that supports it or to the later chapter that enforces it.

The ERD is a proposal for review, not an approved design. This chapter writes no Django model and no migration, and creates no table in the project’s database; models arrive in Chapter 16, the user model in Chapter 17, and migrations in Chapter 18. Some rules are not a matter of structure at all. Stopping two people from taking the last place at the same instant needs transactions, which Chapter 33 adds, and checking that a person may change a record is the work of Chapter 30. Registration windows, how organizers are appointed, and which contact details to collect remain open decisions from Chapter 2. The SQL in this chapter is only what the lab needs; querying records through Django begins in Chapter 19.

PAGE 001

What You Need to Know

From one spreadsheet to related tables

Sam’s spreadsheet is a single table: each row holds one registration, and every column a reader might want sits in the same row. That shape is easy to start with, and it fails in three predictable ways. A fact that appears in many rows, such as Sai’s email address, has to be changed in all of them, and missing one leaves the table contradicting itself. A fact that lives only in a row, such as Raj’s registration, disappears when the row is deleted. And nothing stops a row that should not exist, such as a registration for an event that was never arranged.

New Concept: a relational database

What problem exists? Records that many people read and change must not contradict each other, must survive a restart, and must be refused when they break a rule.

What did people do before? Spreadsheets and flat files, with every fact repeated wherever it was needed and every rule kept in someone’s head.

What is a relational database? A store that keeps each kind of thing in its own table. Each row is one record, and each column holds one kind of value for every row. Tables refer to each other through identifying values instead of copying each other’s data.

Why use one? Each fact is stored once, so it is changed in one place. The database can enforce rules on every row, however that row arrived. Django is built to work with relational databases, and the project uses SQLite now and PostgreSQL from Chapter 32.

Now let’s use it. The rest of this part reads a few small tables and the rules that connect them; How We Build It designs Otahque’s own.

The two shapes are side by side in Figure 15.1. On the right, the event titles, the member email addresses, and the registrations are separate tables. A registration row holds only the identifying numbers of its event and its member, and a status. When Sai changes her email address, one row changes, and every registration that refers to her sees the change. When Raj cancels, his row stays and its status says so.

On the left, one spreadsheet with event, name, and email columns. Sai appears in three rows; two show sai@example.org and the third, for Django night, still shows sai@example.com and is tinted red. Raj’s Python meetup row is crossed out with a dashed red border. Two red notes below say the email was updated in two rows and missed in one, and that Raj’s deleted row leaves no record that he registered. On the right, three green tables: events with ids 7 to 9, members with ids 1 and 2 holding one email address each, and registrations with event_id, member_id, and status columns. Arrows labelled key lead from the event_id column to the events table and from member_id to the members table. Raj’s registration has the status cancelled. A green note says each email is stored once and a cancellation is a status, not a deleted row.
Figure 15.1 — One spreadsheet compared with related tables.

The general rule is one fact in one place. Database designers call the work of reaching it normalization, and Under the Hood names its usual stages. You need only the plain rule: if a value would be repeated in many rows, it probably belongs in a table of its own, and the rows should refer to it.

Entities, attributes, and keys

An entity is a kind of thing the system keeps records about: a member, an event, a registration. Each entity becomes a table. An attribute is one fact about an entity, such as an event’s title or capacity, and becomes a column. Reading Chapter 2 for nouns is a good start, but not every noun earns a table. “Venue” is a noun, yet Otahque’s first release only needs to show where an event takes place, so the location is an attribute of the event. “Attendee” is a noun too, but Chapter 2 defined an attendee as a member registered for a particular event, so an attendee is a member plus a registration, not a third kind of person.

New Concept: primary keys and foreign keys

What problem exists? One row must be able to point at exactly one other row, and keep pointing at it even when that row’s details change.

What did people do before? They identified things by a name or an email address, which change and which two people can share.

What are keys? A primary key is a column whose value identifies one row in its table and never changes. A foreign key is a column in another table that holds a primary key value, so that its row refers to that row.

Why use them? A registration that stores member_id 1 refers to Sai whatever her email address becomes, and the database can check that a member with that key exists.

Now let’s use it. Every entity in this chapter gets a plain numeric primary key called id, the form Django creates by default in Chapter 16.

Choose identity before details. An email address looks unique, and Otahque may well require it to be unique, but it is still a detail a person can change, so it is an attribute with a uniqueness rule, not the key. A title is not even unique: two years of the same meetup can share one. A key such as id carries no meaning at all, which is exactly why it never needs to change.

The foreign key always goes on the side that has many. One event has many registrations, and each registration belongs to one event, so the registration row holds event_id. The event row cannot hold its registrations: it would need a column for each one, and nobody knows in advance how many there will be. Written in SQL, the language relational databases understand, the registration table begins like this. It is a read-only example; you will write and run your own in the lab.

CREATE TABLE registration (
    id INTEGER PRIMARY KEY,
    event_id INTEGER NOT NULL REFERENCES event (id),
    member_id INTEGER NOT NULL REFERENCES member (id),
    status TEXT NOT NULL
);

REFERENCES event (id) declares the foreign key: every value in event_id must match an id in the event table. NOT NULL says the column must have a value, so no registration can belong to no event.

Relationships, cardinality, and optionality

A relationship says how rows of two entities are connected. Two questions describe each end of it. Cardinality asks how many: at most one, or many? Optionality asks whether any must exist: can the number be zero? Say each relationship aloud in both directions before drawing anything. “One event has zero or more registrations” and “each registration belongs to exactly one event” are two readings of the same line.

New Concept: crow’s foot notation

What problem exists? A line between two boxes says that they are related, but not how many rows take part or whether any must.

What did people do before? They wrote the rules in notes beside the drawing, where they drifted away from it.

What is crow’s foot notation? A way of marking both answers at each end of a relationship line. The mark nearer the box gives the maximum: a bar for one, a three-pronged “crow’s foot” for many. The mark further out gives the minimum: a circle for zero, a bar for one.

Why use it? It is a widely used ERD notation, it reads the same on paper and in tools, and the Mermaid text format you will use in the project draws it.

Now let’s use it. Figure 15.2 shows the four ends you will need, and one relationship read in both directions.

Four relationship line ends, each meeting a small box. Two bars mean exactly one. A circle then a bar means zero or one. A bar then a crow’s foot means one or more. A circle then a crow’s foot means zero or more. Below a divider, an Event box and a Registration box are joined by one line: two bars at the Event end and a circle with a crow’s foot at the Registration end. Two sentences read the line both ways: one event has zero or more registrations, and each registration belongs to exactly one event.
Figure 15.2 — Crow’s foot line ends, and one relationship read both ways.

The marks you read are the ones at the far end. To say how many registrations one event has, start at Event and read the marks beside Registration. Most relationships in this book are one-to-many, like this one. A one-to-one relationship, where each side has at most one partner, would suit a member profile; Chapter 20 shows the idea, and Chapter 27 decides whether Otahque needs one. A many-to-many relationship needs the next idea.

When a relationship has facts of its own

A member can register for many events, and an event has many registered members. That is a many-to-many relationship, and no single foreign key can express it: neither table can hold a list of the other’s keys. The usual answer is a table in between, whose rows each pair one member with one event. In Otahque that table is not a mere link, because each pairing has facts of its own: a registration has a status, the time it was made, and, if it was cancelled, the time of cancellation.

New Concept: an association entity

What problem exists? A many-to-many relationship that also has its own facts, such as when it started and whether it still holds.

What did people do before? They stored only the pairing, and kept the extra facts elsewhere or not at all, which is how Raj’s cancellation was lost.

What is an association entity? An entity whose rows each connect one row of one entity with one row of another, and carry the facts about that connection. It has its own primary key and a foreign key to each side.

Why use one? Registration is the centre of Otahque. Its status decides whether a place is counted, and keeping cancelled rows keeps the history that Chapter 2’s cancellation rule asks for.

Now let’s use it. Otahque’s design has two association entities: Registration, between members and events, and Organizer assignment, which records that a member organizes an event until the assignment is revoked.

Keeping cancelled rows raises a question. If Sai cancels and later registers again for the same event, there will be two rows for the same member and event, and that is correct: one cancelled, one active. The rule Otahque needs is narrower than “one row per member and event”. It is “at most one active row per member and event”. The SQLite documentation illustrates the same shape with a team that may have many members but only one leader: the rule applies only to the rows that match a condition. Databases express it with a partial unique index, which you will build in the lab:

CREATE UNIQUE INDEX one_active_registration
    ON registration (event_id, member_id)
    WHERE status = 'active';

Only rows whose status is active are included in this index, and within it each pair of event and member may appear once. Cancelled rows are outside it, so any number of them may exist.

What the database can refuse, and what it cannot

A constraint is a rule the database checks on every row it stores, refusing the change if the rule would be broken. Table 15.1 lists the kinds this chapter uses.

Table 15.1 — Constraints and what each refuses
Constraint What it refuses Otahque example
NOT NULL A missing value A registration with no event
UNIQUE A second row with the same value Two members with one email address
CHECK A row for which a condition is false A capacity of 0, or a status other than active or cancelled
FOREIGN KEY A reference to a row that does not exist A registration for event 99 when there is no event 99
Partial unique index A duplicate among the rows that match a condition A second active registration by Sai for the same event

Constraints matter because they hold whichever code saves the row: a form, the admin, an import script, or a mistake in a view. Django’s own checks, which begin with forms in Chapter 24, give people helpful messages first. The database is the last line of defence, and it applies the same rules every time.

It also has limits. Some of Chapter 2’s rules are about who is acting, or about actions that overlap, and a single row cannot show that they are broken. Table 15.2 names those rules and where the book enforces them.

Table 15.2 — Rules a table structure cannot enforce alone
Rule Why structure is not enough Enforced in
Never more active registrations than capacity The count spans many rows, and two requests can read the same count at once Chapter 33, with transactions on PostgreSQL
Members change only their own registrations Who is asking is not part of the row Chapters 27 and 30
Organizers manage only assigned events Depends on the person making the request Chapter 30
Valid details before publication Needs messages people can act on, and a policy that is still open Chapters 21, 25, and 26

The first row shows a design choice. Otahque stores each event’s capacity, but not the number of places taken. That number is derived: it is counted from the active registrations whenever it is needed. A stored counter would be a second copy of the same fact, which would have to be kept equal to the count on every registration and cancellation. Some systems do keep counters, to avoid counting on every page, and repair them when they drift; that is a trade-off to make with measurements, not at the start.

What an ERD shows

An ERD can be drawn at different levels of detail. A conceptual diagram shows only the entities and how they relate. A logical diagram adds the attributes and the keys. A physical diagram adds the database’s column types, indexes, and storage details. This chapter’s ERD is logical: four entities, their keys and main attributes, and the relationships between them, with the rules beside it. Column types belong to Django’s fields in Chapter 16.

You will record the ERD as text, in a format called Mermaid, which several tools, including GitHub, draw as a diagram. The text itself is the record: it can be reviewed line by line, compared in Git, and read without any tool. Here is the relationship from Figure 15.2 in Mermaid:

erDiagram
    EVENT ||--o{ REGISTRATION : "has"

|| is the exactly-one end at EVENT, and o{ is the zero-or-more end at REGISTRATION. Each two-character mark is read like the drawn ends: the character further from its entity is the minimum, and the one nearer the entity is the maximum.

Python’s sqlite3 module

The lab in this chapter needs a real database that refuses real rows, without touching the project. Python already includes one.

New Tool: Python’s sqlite3 module and an in-memory database

What problem exists? To watch constraints refuse rows, we need a database we can create, break, and throw away freely, without installing a server or touching the project’s db.sqlite3.

What did people do before? They installed a database server, created a practice database, and had to remember to remove it.

What is it? SQLite is a small database engine that keeps a whole database in one file, and Python’s standard library includes it as the sqlite3 module. Connecting to the special name :memory: creates a database that exists only in memory and vanishes when the program ends.

Why use it? There is nothing to install and nothing left behind, and it is the same SQLite engine that Django uses for the project’s development database.

Now let’s use it. Check which SQLite version your Python includes. Run this from the Chapter 14 project folder; it is the same in PowerShell and in macOS/Linux/WSL.

uv run python -m sqlite3 -v
SQLite version 3.53.1

That is the version bundled with Python 3.14.9 on Windows; macOS and Linux builds may report a different one. Django 6.1 supports SQLite 3.37.0 and later, and partial indexes need 3.8.0 or later, so any version Django accepts is enough here. Without -v, python -m sqlite3 opens an interactive shell where you type SQL; type .quit to leave it. The lab uses a small script instead, so that every run starts the same way.

Under the Hood: how the database decides to refuse a row

Before storing a row, SQLite checks each rule in turn. For NOT NULL and CHECK it looks only at the new row. For UNIQUE and the partial unique index, it looks the new values up in the index that backs the rule and refuses the row if a matching entry exists; a partial index simply leaves out the rows that do not match its condition. For a foreign key, it looks for a row in the parent table with that primary key and refuses the change if there is none. A refusal reaches Python as an sqlite3.IntegrityError, and the change is not stored. One rule surprises almost everyone: for compatibility with old databases, SQLite does not check foreign keys unless the connection asks it to, through a setting called a pragma, and that setting cannot be changed in the middle of a transaction. Django’s SQLite backend turns the check on for every connection it opens, but a connection you open yourself with sqlite3.connect() starts with it off. Finally, the plain rule of one fact in one place is what database theory calls normalization; its usual stages are named first, second, and third normal form, and this book uses the plain rule rather than the formal definitions.

The pragma looks like this. The first line asks for the current setting, which is 0 (off) on a new connection; the second turns checking on for that connection only.

PRAGMA foreign_keys;
PRAGMA foreign_keys = ON;

Django’s own line is in its source, in django/db/backends/sqlite3/base.py, inside the get_new_connection method of the version installed in your project’s .venv folder. It is why the project will never need the pragma, and why your lab will.

In practice: keeping personal data where it belongs

Situation. Each entity in the design is a place where personal data could end up. It is tempting to add a phone number, a postal address, or a date of birth to the member entity in case they are useful later.

Application. Store only what a Chapter 2 rule needs, in the one entity it describes. The member entity holds an email address and a display name; a registration holds no copy of either, only member_id. Organizers will see participants through registrations, under the access rules of Chapter 30, rather than through a copied list.

Consideration. Chapter 2 left the exact contact details as an open decision, so the ERD names that question instead of guessing. Every column added later is something to protect, to explain to the people it describes, and eventually to delete.

You now have the vocabulary to design Otahque’s first data model: tables, keys, relationships, association entities, constraints, and the rules that need more than structure. How We Build It applies it to Chapter 2’s rules and checks the result against a real database.

PAGE 002

How We Build It

Start from Chapter 14, in the directory containing manage.py, with your own .env, the locked environment, 18 passing tests, and the Chapter 14 work committed to your Git repository. This chapter changes no Python, template, or stylesheet file. It adds one document to the project, docs/design/erd.md, and one throwaway script, relational_lab.py, in a practice folder beside the project folder, outside it, so that the lab never becomes part of Otahque. At the end, the design is committed, the lab shows the database refusing each bad row, and the project still has no tables.

The Custom Way

This illustration shows Sam’s spreadsheet as a single database table; do not add it to the project:

CREATE TABLE sheet (
    event_title TEXT,
    event_date TEXT,
    member_name TEXT,
    member_email TEXT
);
-- Raj cancels: his row, and every fact in it, is gone.
DELETE FROM sheet WHERE member_name = 'Raj';

It is quick to create and it accepts anything. Every event detail and every email address is repeated in each row that needs it. No column identifies a person, so two Sais cannot be told apart, and a deleted row leaves no trace that it existed. Nothing refuses an empty email address or an event that was never arranged. The approach below starts from the rules instead, gives each kind of thing its own table and key, and checks the result against a real database before anything reaches Django.

The Recorded Way

Design chapters build documents, so this part designs and records rather than writing Django code. Each step either adds to docs/design/erd.md or tests an idea in the lab.

Step 1: Check the starting point

Run the Chapter 14 tests beside manage.py, in PowerShell, a macOS shell, or Linux/WSL Bash:

uv run python manage.py test events

Expected result, shortened with ... where lines are left out:

Found 18 test(s).
System check identified no issues (0 silenced).
..................
...
Ran 18 tests in ...

OK

Next, look for a file called db.sqlite3 beside manage.py. You probably have one: Chapter 6 explained that the development server may create an empty database file while checking migrations. A file is fine; tables are what this chapter must not create yet. If the file exists, ask SQLite to list the names of everything in it. The command is split over two lines, with each shell’s own continuation character. In PowerShell, beside manage.py:

uv run python -m sqlite3 db.sqlite3 `
    "SELECT name FROM sqlite_schema"

In a macOS shell or Linux/WSL Bash, beside manage.py:

uv run python -m sqlite3 db.sqlite3 \
    "SELECT name FROM sqlite_schema"

Expected result: nothing at all. sqlite_schema is SQLite’s own list of the tables and indexes in a database, so an empty answer means there are none. If there is no db.sqlite3, skip this check; do not run the command, because connecting to a missing file creates an empty one.

Common Error: running migrate to get a database

It is tempting to run uv run python manage.py migrate so that the database has something in it. Do not do it yet. migrate creates Django’s built-in tables, including a table of users, and Chapter 17 must choose Otahque’s user model before those tables exist, because changing the user model afterwards is difficult. A second trap: SQLite’s own command-line program accepts commands such as .tables, but python -m sqlite3 treats its argument as SQL, so .tables there fails with OperationalError and a syntax error near “.”. Use the SELECT above.

If the query lists tables such as django_migrations or auth_user, migrate has already been run. Keep the file: rename it, for example to db-before-ch15.sqlite3, so that the project starts Chapter 17 with no tables, and keep the renamed copy until Chapter 17 confirms that nothing in it is needed.

Finally, create the practice folder beside the project folder. The same command works in PowerShell and in a macOS shell or Linux/WSL Bash; PowerShell also prints a short table describing the new folder:

mkdir ../practice

Step 2: Find the entities

Open Chapter 2’s rules and Sam’s spreadsheet, and list every noun that names something Otahque might store. Then decide, for each, whether it is a kind of thing with its own facts and identity, a fact about something else, or outside the first release. Table 15.3 records our decisions.

Table 15.3 — Candidate nouns, kept and rejected
Noun Decision Reason
Member Entity A person with an account; registrations and assignments refer to it
Event Entity Has its own facts: title, start, end, time zone, location, capacity, status
Registration Entity A member's place in an event, with its own status and times
Organizer assignment Entity Which member organizes which event, until revoked (PR-4)
Attendee Not an entity A member with an active registration for that event
Venue, location Attribute The first release only shows where an event takes place
Capacity, status Attributes Facts about one event, or about one registration
Category, tag Out of scope Not in the first release; Chapter 20's optional lab builds topics in a copy of the project
Attendance, waitlist Out of scope Event-day operations, Chapter 46
Community Out of scope One community for now; several communities in Chapters 67 and 68

Create the folders docs/design beside manage.py, and in them a file called erd.md. Start it with its status, so that nobody mistakes it for an approved design:

# Otahque data model (ERD)

Status: Proposed, for review. No table exists yet.
Scope: the first release (one community, free events).
Sources: Chapter 2 rules PR-1 to PR-6.

Step 3: Add keys and relationships

Give each entity an id primary key. Then read each relationship aloud in both directions, and put the foreign key on the side that has many:

  • One member makes zero or more registrations; each registration is made by exactly one member.
  • One event has zero or more registrations; each registration is for exactly one event.
  • One member holds zero or more organizer assignments; each assignment belongs to exactly one member.
  • One event has zero or more organizer assignments; each assignment is for exactly one event.

An event may have no organizer assignment at all, because who appoints organizers, and whether every event needs one, is still an open decision. Add the diagram section to erd.md, below the status lines. The diagram sits between a line ~~~mermaid and a line ~~~, which Markdown treats as a fenced block and Mermaid-aware viewers draw:


## Diagram

~~~mermaid
erDiagram
    MEMBER ||--o{ REGISTRATION : "makes"
    EVENT ||--o{ REGISTRATION : "has"
    MEMBER ||--o{ ORGANIZER_ASSIGNMENT : "holds"
    EVENT ||--o{ ORGANIZER_ASSIGNMENT : "is run through"
    MEMBER {
        int id PK
        text email UK
        text display_name
    }
    EVENT {
        int id PK
        text title
        datetime starts_at "an instant, in UTC"
        datetime ends_at "after starts_at, in UTC"
        text timezone "IANA name"
        text location
        int capacity "more than 0"
        text status "draft, published, cancelled"
    }
    REGISTRATION {
        int id PK
        int event_id FK
        int member_id FK
        text status "active or cancelled"
        datetime registered_at
        datetime cancelled_at "empty until cancelled"
    }
    ORGANIZER_ASSIGNMENT {
        int id PK
        int event_id FK
        int member_id FK
        datetime assigned_at
        datetime revoked_at "empty while current"
    }
~~~

Each attribute line gives a type, a name, an optional key mark (PK, FK, or UK for unique), and an optional note in quotes. The types are words for people, not database column types; Django’s fields decide those in Chapter 16. starts_at and ends_at are instants, stored in UTC, and an event ends after it starts. timezone keeps the event’s own time-zone name, used for both, such as Europe/London, so pages can show the local time Chapter 2 asked for. Figure 15.3 draws the same design.

Four green entity boxes. MEMBER, on the left, has id (PK), email (UK), and display_name. EVENT, on the right, has id (PK), title, starts_at, ends_at, timezone, location, capacity, and status. Between them, REGISTRATION has id (PK), event_id (FK), member_id (FK), status, registered_at, and cancelled_at, and ORGANIZER ASSIGNMENT below it has id (PK), event_id (FK), member_id (FK), assigned_at, and revoked_at. Each line runs from MEMBER or EVENT, marked with two bars for exactly one, to the matching foreign-key row of REGISTRATION or ORGANIZER ASSIGNMENT, marked with a circle and a crow’s foot for zero or more. Orange notes say: one active registration per member and event, through a partial unique index; one current assignment per member and event; and capacity is stored while places taken are counted from active registrations.
Figure 15.3 — The proposed first-release ERD.

Common Error: a line without its marks, or a key on the wrong side

A line between two boxes with no marks at its ends says nothing about how many rows take part, and two readers will assume different answers. Mark both ends. If you find yourself wanting an event column that holds several registration numbers, the foreign key is on the wrong side: it belongs in the registration, the side that has many. And if a relationship needs a status or a time, it is an entity of its own, not a bare link.

Step 4: Write the lab test-first

A diagram can be wrong in ways that only a database reveals. The lab writes down, first, the rows the design says must be refused. Then it runs them against tables that have columns but almost no rules, and we watch every bad row being accepted. That is the red stage, the same habit as a test written before the code since Chapter 9.

Create relational_lab.py in the practice folder:

"""Chapter 15 lab: see which bad rows are refused."""
import sqlite3

SCHEMA = """
CREATE TABLE member (
    id INTEGER PRIMARY KEY,
    email TEXT NOT NULL UNIQUE
);
CREATE TABLE event (
    id INTEGER PRIMARY KEY,
    title TEXT NOT NULL,
    capacity INTEGER NOT NULL
);
CREATE TABLE registration (
    id INTEGER PRIMARY KEY,
    event_id INTEGER NOT NULL,
    member_id INTEGER NOT NULL,
    status TEXT NOT NULL
);
"""

GOOD_ROWS = [
    "INSERT INTO member VALUES (1, 'sai@example.org')",
    "INSERT INTO event VALUES (7, 'Python meetup', 2)",
    "INSERT INTO registration VALUES (1, 7, 1, 'active')",
]

BAD_ROWS = {
    "orphan registration": "INSERT INTO registration"
        " VALUES (2, 99, 1, 'active')",
    "capacity of 0": "INSERT INTO event"
        " VALUES (8, 'Data night', 0)",
    "unknown status": "INSERT INTO registration"
        " VALUES (3, 7, 1, 'maybe')",
    "second active place": "INSERT INTO registration"
        " VALUES (4, 7, 1, 'active')",
}


def fresh_database():
    db = sqlite3.connect(":memory:", autocommit=True)
    db.executescript(SCHEMA)
    for sql in GOOD_ROWS:
        db.execute(sql)
    return db


def report(name, error):
    kind, _, detail = str(error).partition(": ")
    print(f"refused   {name}: {kind}")
    if detail:
        print(f"          {detail}")


for name, sql in BAD_ROWS.items():
    db = fresh_database()
    try:
        db.execute(sql)
        print(f"accepted  {name}")
    except sqlite3.IntegrityError as error:
        report(name, error)
    db.close()

Read it from the top. SCHEMA holds the SQL that creates the three tables; only NOT NULL and the email’s UNIQUE are rules so far. GOOD_ROWS are a member (Sai, number 1), an event (number 7, with two places), and Sai’s active registration. BAD_ROWS names four rows that break a Chapter 2 rule, each written as two string literals side by side, which Python joins into one string so that each line stays short: a registration for event 99, which does not exist; an event with no places; a status Otahque does not have; and a second active registration by Sai for the same event. fresh_database() creates a new database in memory, with autocommit=True so that each statement takes effect on its own, builds the schema, and adds the good rows. The loop gives each bad row its own fresh database, so the bad rows cannot affect each other, and prints whether the database accepted or refused it. report() splits SQLite’s message at its first colon so that each line fits on the page.

Because every run builds its database from SCHEMA, nothing carries over between runs. Each change you make in Step 5 changes what the next run creates; there is never an old table to alter. Run the lab from the project folder, so that uv uses the project’s Python. The same command works in PowerShell and in a macOS shell or Linux/WSL Bash:

uv run python ../practice/relational_lab.py
accepted  orphan registration
accepted  capacity of 0
accepted  unknown status
accepted  second active place

Every bad row is accepted. That is the result we expect: nothing in the schema says otherwise yet.

Step 5: Add structure until each bad row is refused

Make four edits, and rerun the lab after each.

Common Error: foreign keys declared but not checked

After the first edit below, the schema declares foreign keys. If you add the REFERENCES clauses but not the PRAGMA line, the orphan registration is still accepted, with no error or warning, because SQLite checks foreign keys only on connections that ask for it. Both lines of the edit are needed. Django asks on every connection it opens, which is why the project will not need this line.

First, the foreign keys. In SCHEMA, give the registration table’s two key columns their references:

    event_id INTEGER NOT NULL REFERENCES event (id),
    member_id INTEGER NOT NULL REFERENCES member (id),

Then, in fresh_database(), turn foreign-key checking on straight after connecting:

    db = sqlite3.connect(":memory:", autocommit=True)
    db.execute("PRAGMA foreign_keys = ON")

Run the lab again:

refused   orphan registration: FOREIGN KEY constraint failed
accepted  capacity of 0
accepted  unknown status
accepted  second active place

Second, the checks. A CHECK constraint can be given a name with CONSTRAINT, and SQLite then uses that name in its message, which makes refusals easy to recognize. Change the end of the event table:

    capacity INTEGER NOT NULL,
    CONSTRAINT positive_capacity CHECK (capacity > 0)
);

and the end of the registration table:

    status TEXT NOT NULL,
    CONSTRAINT known_status
        CHECK (status IN ('active', 'cancelled'))
);

Run the lab:

refused   orphan registration: FOREIGN KEY constraint failed
refused   capacity of 0: CHECK constraint failed
          positive_capacity
refused   unknown status: CHECK constraint failed
          known_status
accepted  second active place

Third, the partial unique index. Add it at the end of SCHEMA, after the registration table and before the closing """:

CREATE UNIQUE INDEX one_active_registration
    ON registration (event_id, member_id)
    WHERE status = 'active';
"""
refused   orphan registration: FOREIGN KEY constraint failed
refused   capacity of 0: CHECK constraint failed
          positive_capacity
refused   unknown status: CHECK constraint failed
          known_status
refused   second active place: UNIQUE constraint failed
          registration.event_id, registration.member_id

All four bad rows are now refused, each by the rule written for it. For a unique index, SQLite names the columns rather than the index.

Common Error: uniqueness that blocks registering again

Writing UNIQUE (event_id, member_id) in the registration table also refuses the second active place, and looks finished. But it refuses every second row for the same member and event, cancelled or not, so a member who cancels can never register again, and the history Chapter 2 asked for has no room. The rule is about active rows only, which is what the partial index’s WHERE says. The last edit tests exactly this.

Fourth, the case that must succeed. Add this block at the end of the file. Sai cancels her registration, registers again for the same event, and the lab shows her history and one count of the places taken:


print()
print("Sai cancels, then registers again:")
db = fresh_database()
db.execute("UPDATE registration SET status = 'cancelled'"
           " WHERE id = 1")
db.execute("INSERT INTO registration"
           " VALUES (5, 7, 1, 'active')")
rows = db.execute("SELECT id, status FROM registration")
for row in rows:
    print(row)
places = db.execute("""
    SELECT event.title, event.capacity,
           COUNT(registration.id)
    FROM event
    JOIN registration ON registration.event_id = event.id
    WHERE registration.status = 'active'
    GROUP BY event.id
""").fetchall()
print(places)
db.close()

The query is the first join of the book: JOIN ... ON puts each registration beside the event its event_id names, WHERE keeps only active registrations, and GROUP BY event.id with COUNT counts them per event. This is the derived count from What You Need to Know.

Run the lab one last time:

refused   orphan registration: FOREIGN KEY constraint failed
refused   capacity of 0: CHECK constraint failed
          positive_capacity
refused   unknown status: CHECK constraint failed
          known_status
refused   second active place: UNIQUE constraint failed
          registration.event_id, registration.member_id

Sai cancels, then registers again:
(1, 'cancelled')
(5, 'active')
[('Python meetup', 2, 1)]

The cancelled row is kept, the new active row is accepted, and the Python meetup has one of its two places taken. The complete lab, as it should now read:

"""Chapter 15 lab: see which bad rows are refused."""
import sqlite3

SCHEMA = """
CREATE TABLE member (
    id INTEGER PRIMARY KEY,
    email TEXT NOT NULL UNIQUE
);
CREATE TABLE event (
    id INTEGER PRIMARY KEY,
    title TEXT NOT NULL,
    capacity INTEGER NOT NULL,
    CONSTRAINT positive_capacity CHECK (capacity > 0)
);
CREATE TABLE registration (
    id INTEGER PRIMARY KEY,
    event_id INTEGER NOT NULL REFERENCES event (id),
    member_id INTEGER NOT NULL REFERENCES member (id),
    status TEXT NOT NULL,
    CONSTRAINT known_status
        CHECK (status IN ('active', 'cancelled'))
);
CREATE UNIQUE INDEX one_active_registration
    ON registration (event_id, member_id)
    WHERE status = 'active';
"""

GOOD_ROWS = [
    "INSERT INTO member VALUES (1, 'sai@example.org')",
    "INSERT INTO event VALUES (7, 'Python meetup', 2)",
    "INSERT INTO registration VALUES (1, 7, 1, 'active')",
]

BAD_ROWS = {
    "orphan registration": "INSERT INTO registration"
        " VALUES (2, 99, 1, 'active')",
    "capacity of 0": "INSERT INTO event"
        " VALUES (8, 'Data night', 0)",
    "unknown status": "INSERT INTO registration"
        " VALUES (3, 7, 1, 'maybe')",
    "second active place": "INSERT INTO registration"
        " VALUES (4, 7, 1, 'active')",
}


def fresh_database():
    db = sqlite3.connect(":memory:", autocommit=True)
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SCHEMA)
    for sql in GOOD_ROWS:
        db.execute(sql)
    return db


def report(name, error):
    kind, _, detail = str(error).partition(": ")
    print(f"refused   {name}: {kind}")
    if detail:
        print(f"          {detail}")


for name, sql in BAD_ROWS.items():
    db = fresh_database()
    try:
        db.execute(sql)
        print(f"accepted  {name}")
    except sqlite3.IntegrityError as error:
        report(name, error)
    db.close()

print()
print("Sai cancels, then registers again:")
db = fresh_database()
db.execute("UPDATE registration SET status = 'cancelled'"
           " WHERE id = 1")
db.execute("INSERT INTO registration"
           " VALUES (5, 7, 1, 'active')")
rows = db.execute("SELECT id, status FROM registration")
for row in rows:
    print(row)
places = db.execute("""
    SELECT event.title, event.capacity,
           COUNT(registration.id)
    FROM event
    JOIN registration ON registration.event_id = event.id
    WHERE registration.status = 'active'
    GROUP BY event.id
""").fetchall()
print(places)
db.close()

The lab proves what structure can do, not what it cannot. One connection ran one statement at a time, so it says nothing about two people taking the last place at once; that is Chapter 33’s work.

Step 6: Complete the ERD, check it, and commit

Finish erd.md with the rules the structure holds, the rules it cannot hold and where they will be enforced, the open questions, and what is out of scope. Add this below the diagram:


## Rules the structure holds

- PR-1: at most one active registration per member and
  event (partial unique index on event_id and member_id
  where status is active).
- PR-1, PR-2: a registration refers to a real event and
  a real member (foreign keys).
- PR-2: a cancelled registration keeps its row, with
  its status and cancelled_at; it is never deleted.
- PR-4: at most one current assignment per member and
  event (partial unique index where revoked_at is empty).
- Capacity is more than 0; an event ends after it
  starts; each status comes from its fixed list
  (CHECK constraints).
- Intent: deleting an event or member that has
  registrations is refused, so history survives.

## Rules that need more than structure

- PR-2, cancelled_at filled exactly when status is
  cancelled: a CHECK constraint, Chapter 21.
- PR-3, never more active places than capacity:
  transactions, Chapter 33.
- PR-4, own registrations and assigned events only:
  Chapters 27 and 30.
- PR-5, valid details before publication; drafts hidden:
  Chapters 21, 25, and 26.
- PR-6, access administration: Chapters 23 and 30.

## Open questions

- Which contact details, beyond an email address?
- Are addresses that differ only in letter case one
  member? Decided in Chapter 21, before sign-up.
- Who appoints organizers, and must an event have one?
- When registration opens and closes (Chapter 2 policy).
- What happens to active registrations when an event
  is cancelled?

## Out of scope for this release

- Category and tag: not first-release requirements.
- Venue: the location is an attribute of the event;
  an online event records Virtual as its location.
- Attendance, check-in, and waitlists: Chapter 46.
- Communities and tenancy: Chapters 67 and 68.
- Audit records: Chapter 65.

The “intent” line records a decision for Chapter 20, where Django’s on_delete setting will make it real. Figure 15.4 traces each Chapter 2 rule through the structure to the later control that completes it. No rule is finished by structure alone: registration still needs its eligibility checks in Chapter 31, even though the database already refuses a duplicate.

Five numbered rows, each running from an orange rule card through a green structure card to a dashed grey card for a later chapter. Rule 1, PR-1 one active place: foreign keys and a partial unique index, then eligibility checks in Chapter 31. Rule 2, PR-2 cancellation: status and cancelled_at with the row kept, then the cancel workflow in Chapter 31. Rule 3, PR-3 never over capacity: capacity stored and the count derived, then transactions in Chapter 33. Rule 4, PR-4 own records and assigned events: member and event keys on each row, then access checks in Chapters 27 and 30. Rule 5, PR-5 publication: the event status draft or published, then validation in Chapters 21 to 26.
Figure 15.4 — Each rule traced to its structure and its later control.

Now review the file as plain text, which is the check that matters; a drawing is optional. Read erd.md from the top and confirm five things: four entities; one primary key each; every foreign key on the many side, matching a relationship line; marks at both ends of every line; and the active-registration rule stated. If you use GitHub or another Mermaid-aware viewer, you may also see it drawn, but the text is the record.

Common Error: calling the ERD approved, or committing the lab

The status line says Proposed, and it should stay that way until someone responsible for the product has reviewed it; this book records decisions, it does not invent approvals. The lab is practice. It lives outside the project folder so that it is never committed with Otahque, and nothing in the project imports it.

Rerun the tests and, if db.sqlite3 exists, the table query from Step 1. Expect the same results as before: 18 tests pass, and the query prints nothing. Then check what Git sees:

git status --short
?? docs/

Only the new docs folder is listed. The Git Commit section in Checkpoint: Quiz and Challenge records it.

When something goes wrong

Table 15.4 — Design and lab problems and safe recovery
Symptom Likely cause Safe recovery
The orphan registration is still accepted The PRAGMA line is missing, or comes after other statements Put it straight after connecting, as in the listing, and rerun
A second active registration is accepted The index lacks its WHERE clause, or names other columns Compare the CREATE UNIQUE INDEX lines with the listing
Registering again after cancelling raises IntegrityError UNIQUE (event_id, member_id) on the table instead of the partial index Remove the table rule; use the partial index
sqlite3.OperationalError: near ... syntax error A typo in SCHEMA, such as a missing comma between two columns Read the line the message names; every run starts fresh, so nothing is damaged
The query in Step 1 lists tables migrate was run earlier Rename the file and keep it until Chapter 17; do not delete it now
OperationalError near "." from python -m sqlite3 A command such as .tables was passed as SQL Use the SELECT on sqlite_schema from Step 1
can't open file ... relational_lab.py Run from the wrong folder Run from the folder with manage.py; the practice folder is beside it
A relationship cannot be drawn without a list column The foreign key is on the wrong side, or a link needs its own entity Move the key to the many side, or add an association entity
A rule has no structure in the trace It depends on who acts or when, not on one row Record the later chapter that enforces it; do not invent a column
PAGE 003

Verify Your Work

Work through Table 15.5 from the project folder. The lab rows check what the database refuses; the document rows check what a reviewer will read; the project rows check that nothing else changed.

Table 15.5 — Verification checklist for Chapter 15
Check Command or action Expected result
Tests unchanged uv run python manage.py test events 18 tests, OK
No tables yet The Step 1 query, if db.sqlite3 exists No output
Red stage seen The Step 4 run, before any edit Four accepted lines
Each refusal named uv run python ../practice/relational_lab.py Four refused rows: FOREIGN KEY, positive_capacity, known_status, UNIQUE
History kept The last block of the lab output (1, 'cancelled'), (5, 'active'), and one of two places taken
Diagram complete Read erd.md as text Four entities, a PK each, FKs on the many side, marks at both ends
Rules traced Compare erd.md with Figure 15.4 PR-1 to PR-6 each have a structure, a later chapter, or both
Status honest First lines of erd.md Status: Proposed
Only the document added git status --short ?? docs/ before the commit; nothing else
PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 1 Why is a member’s email address not the member’s primary key?

Flip to check your answerFold answer back

Answer. A primary key must identify one row and never change. A person can change their email address, so it is an attribute with a uniqueness rule. A meaningless id never needs to change, so every registration that refers to it stays correct.

Que. 2 Which table holds the foreign key between events and registrations, and why?

Flip to check your answerFold answer back

Answer. The registration table, as event_id. One event has many registrations, and the many side holds the key; an event row would need an unknown number of columns to list its registrations.

Que. 3 Why does cancelling change a status instead of deleting the registration?

Flip to check your answerFold answer back

Answer. A deleted row leaves no trace, so the member’s history and the reason a place was released are lost. A status, with cancelled_at, keeps the history Chapter 2 asked for, and the partial unique index still allows the member to register again.

Que. 4 The lab declared foreign keys with REFERENCES, yet the orphan registration was accepted. What was missing?

Flip to check your answerFold answer back

Answer. PRAGMA foreign_keys = ON on that connection. SQLite checks foreign keys only on connections that turn the check on. Django’s SQLite backend does this for every connection it opens.

Que. 5 Why can no constraint in this chapter stop two people from taking the last place?

Flip to check your answerFold answer back

Answer. The capacity rule spans many rows: it compares a count of active registrations with the event’s capacity. Each constraint here looks at one row, or at duplicates of one row. Two requests can each count one free place before either saves, so the protection needs a transaction that locks and rechecks, which Chapter 33 adds.

Mini-Challenge

Que. 6 Organizer assignment is in the ERD but not in the lab. Copy the lab to ../practice/challenge_lab.py, and leave the original as it is. In the copy, add an organizer_assignment table with its own key, foreign keys to the event and the member, assigned_at, and revoked_at, which stays empty while the assignment is current. Add a partial unique index so that a member has at most one current assignment per event. Then add a good row (Sai organizes event 7) and a bad row (a second current assignment for the same pair), and show that a revoked assignment followed by a new one is accepted.

Flip to check your answerFold answer back

Answer. Add the table and index to SCHEMA, after the registration index. An empty value in SQL is NULL, and the test for it is IS NULL:

CREATE TABLE organizer_assignment (
    id INTEGER PRIMARY KEY,
    event_id INTEGER NOT NULL REFERENCES event (id),
    member_id INTEGER NOT NULL REFERENCES member (id),
    assigned_at TEXT NOT NULL,
    revoked_at TEXT
);
CREATE UNIQUE INDEX one_current_assignment
    ON organizer_assignment (event_id, member_id)
    WHERE revoked_at IS NULL;
"""

Add the good row to GOOD_ROWS, and the bad row to BAD_ROWS:

    "INSERT INTO organizer_assignment"
    " VALUES (1, 7, 1, '2026-11-04', NULL)",

    "second current assignment":
        "INSERT INTO organizer_assignment"
        " VALUES (2, 7, 1, '2026-11-05', NULL)",

As in BAD_ROWS, two string literals side by side are joined into one string. The first addition goes at the end of GOOD_ROWS, the second at the end of BAD_ROWS. Finally, add this block at the end of the file:


print()
print("The assignment is revoked, then made again:")
db = fresh_database()
db.execute("UPDATE organizer_assignment"
           " SET revoked_at = '2026-11-06' WHERE id = 1")
db.execute("INSERT INTO organizer_assignment"
           " VALUES (3, 7, 1, '2026-11-07', NULL)")
for row in db.execute(
        "SELECT id, revoked_at FROM organizer_assignment"):
    print(row)
db.close()

Run uv run python ../practice/challenge_lab.py. The four earlier refusals are unchanged; the new lines are:

refused   second current assignment: UNIQUE constraint failed
          organizer_assignment.event_id, ...
...
The assignment is revoked, then made again:
(1, '2026-11-06')
(3, None)

The output is shortened with ...: the second line goes on to name organizer_assignment.member_id, and the lines between are the earlier output. Python shows SQL’s NULL as None. The same partial-index pattern serves both association entities, with a different condition: a status for registrations, an empty revoked_at for assignments. Dates here are plain text for the lab; Django stores real date-times from Chapter 16.

What We Learned

  • A relational database keeps each kind of thing in its own table and each fact in one place, so a change is made once and cannot leave copies that disagree.
  • A primary key identifies one row and never changes; a foreign key, on the side that has many, refers to it.
  • Crow’s foot marks give each end of a relationship its maximum (nearer the box) and minimum (further out); read every relationship in both directions.
  • A relationship with facts of its own, such as a registration’s status and times, is an association entity with its own key.
  • Constraints refuse bad rows whatever code saves them, but rules about who acts, or about actions that overlap, need later controls.
  • SQLite checks foreign keys only when a connection asks; Django asks for its own connections, and the lab had to ask for itself.
  • The ERD is a reviewed, versioned proposal with its status, open questions, and out-of-scope list written down.

Key terms

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

Table 15.6 — Key terms from Chapter 15
Term Meaning
Relational database A store that keeps each kind of thing in a table and links tables through keys.
Table, row, column One kind of thing; one record of it; one kind of value for every record.
Entity, attribute A kind of thing a system records; one fact about it.
Primary key A column whose value identifies one row and never changes.
Foreign key A column holding another table's primary key, so its row refers to that row.
Cardinality How many rows may take part at one end of a relationship: at most one, or many.
Optionality Whether any row must take part: can the number be zero?
Crow's foot notation Marks at each end of a relationship line for its minimum and maximum.
Association entity An entity that connects two others and carries the facts about each connection.
Constraint A rule the database checks on every row, refusing changes that break it.
Partial unique index A uniqueness rule that applies only to rows matching a condition.
Derived value A value computed from stored data when needed, rather than stored itself.
ERD Entity-relationship diagram: the kinds of things stored, their keys, and how they relate.
In-memory database A database that exists only while the program runs.
Pragma A SQLite setting for one connection, such as foreign-key checking.
Join A query that combines rows of two tables through matching keys.

Readiness checkpoint: you are ready for Chapter 16 when docs/design/erd.md is committed with status Proposed, your lab prints the refusals and the history shown in Step 5, all 18 tests pass, and db.sqlite3, if it exists, has no tables. Explain, in a sentence, why the capacity rule needs more than a constraint. Return to the relevant step if any result is missing.

Git Commit

Stage the new document and check what is staged, in PowerShell, a macOS shell, or Linux/WSL Bash, beside manage.py:

git add docs/design/erd.md
git status --short
A  docs/design/erd.md

A marks a file staged to be added. The practice folder is outside the project, so Git never sees it. Then record the commit:

git commit -m "Add the proposed first-release ERD"
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 and L2 check what you have just learned. L3 asks you to reason about a failure that tests rarely catch. L4 and L5 look ahead to a growing application: attempt them now, and return to them later. They are extension questions, not a gate to the next chapter. Each code proof is a short file in the practice folder; run it from the project folder with uv run python ../practice/ followed by the file name, in PowerShell, a macOS shell, or Linux/WSL Bash.

L1 (Junior): What are primary and foreign keys, and which side of a one-to-many relationship holds the foreign key?

What the interviewer is testing: Can you explain identity and reference, and place a key correctly?

Flip to check your answerFold answer back

Perfect answer: A primary key is the column whose value identifies one row in its table; it must be unique, present, and stable, so a meaningless number is usually better than a name or an email address. A foreign key is a column in another table that holds such a value, so its row refers to exactly one row elsewhere, and the database can refuse a reference to a row that does not exist. In a one-to-many relationship the foreign key goes on the many side: each registration holds the event_id of its one event, because the event cannot hold a variable number of registration columns.

Table 15.7 — Primary and foreign keys compared
Question Primary key Foreign key
Lives in The table it identifies The table that refers
Unique in its table Yes No: many rows may refer to one row
May be empty No Only if the relationship is optional
Database checks Uniqueness and presence That the referred-to row exists
Otahque example event.id registration.event_id

Behind the scenes:

insert a registration with event_id 99
look up 99 in event's primary key index
not found -> refuse the row: FOREIGN KEY constraint failed
found -> store the row

Code proof: a reference to a missing event is refused, and the valid one stays:

import sqlite3

db = sqlite3.connect(":memory:", autocommit=True)
db.execute("PRAGMA foreign_keys = ON")
db.execute("CREATE TABLE event (id INTEGER PRIMARY KEY)")
db.execute("""CREATE TABLE registration (
    id INTEGER PRIMARY KEY,
    event_id INTEGER NOT NULL REFERENCES event (id))""")
db.execute("INSERT INTO event VALUES (7)")
db.execute("INSERT INTO registration VALUES (1, 7)")
try:
    db.execute("INSERT INTO registration VALUES (2, 99)")
except sqlite3.IntegrityError as error:
    print(error)
print(db.execute("SELECT * FROM registration").fetchall())
FOREIGN KEY constraint failed
[(1, 7)]

Common mistakes:

  • Using an email address or a title as the primary key.
  • Putting the foreign key on the one side, and then needing a list column.
  • Assuming SQLite checks a declared foreign key without the pragma.

Follow-up the interviewer might ask:

  • “When might a primary key made of two columns make sense?”
  • “What should happen to registrations when their event is deleted?”

L2 (Mid-Level): Why model Registration as an entity rather than a plain many-to-many link between members and events?

What the interviewer is testing: Can you recognize a relationship that carries its own facts and history?

Flip to check your answerFold answer back
A member registers for an event. The pairing has facts of its own, a status and times. So Registration becomes an entity with its own key and a foreign key to each side. Cancelling changes the status and the history stays. A bare link table, holding only the two keys, could not record any of that.
Figure 15.5 — Why the pairing becomes an entity.

Perfect answer: Members and events are many-to-many, so some table in the middle must pair them. If that pairing had no facts, a plain link holding the two keys would do, and Django can create one for you. But in Otahque the pairing is the most important record in the product: it has a status that decides whether a place is counted, a time it was made, and a time it was cancelled. Those facts belong to the pairing, not to either side. As its own entity, Registration has its own key and two foreign keys, can be cancelled by status rather than deleted, and can appear more than once for the same pair over time, with a partial unique index allowing only one active row. That keeps the history a support request or a dispute will need.

Behind the scenes:

plain link: (member_id, event_id) and nothing else
entity: id, member_id, event_id, status, times
cancel: change the status; the row stays
again: a new active row; the old one is history

Code proof: Raj, member 2, cancels and registers again; both rows remain:

import sqlite3

db = sqlite3.connect(":memory:", autocommit=True)
db.execute("""CREATE TABLE registration (
    id INTEGER PRIMARY KEY, event_id INTEGER,
    member_id INTEGER, status TEXT)""")
db.executemany(
    "INSERT INTO registration VALUES (?, ?, ?, ?)",
    [(1, 7, 2, "cancelled"), (2, 7, 2, "active")],
)
for row in db.execute(
        "SELECT * FROM registration WHERE member_id = 2"):
    print(row)
(1, 7, 2, 'cancelled')
(2, 7, 2, 'active')

The question marks are placeholders: sqlite3 fills them from the tuples, safely, in order. Never build SQL by pasting values into the string.

Common mistakes:

  • Storing the status on the member or the event, where it cannot belong to one pairing.
  • Deleting the link row to cancel, and losing the history.
  • Making the pair unique for ever, so nobody can register again.

Follow-up the interviewer might ask:

  • “How would you show a member their registration history?”
  • “What other relationship in Otahque carries its own facts?”

L3 (Senior): How do you guarantee one active registration per member and event while keeping history, and why is an application check alone not enough?

What the interviewer is testing: Can you see why check-then-insert fails when requests overlap, and put the guarantee where it holds?

Flip to check your answerFold answer back
Two requests each check for an active registration. Both see none, so both insert. The partial unique index sees both inserts, stores one row, and refuses the other. The view then turns the refusal into a helpful message.
Figure 15.6 — Two overlapping requests meet the partial unique index.

Perfect answer: Keep every registration row and express the rule in the database as a partial unique index on event and member, limited to rows whose status is active. Cancelled rows fall outside it, so history and re-registration both work. An application check, “is there already an active registration?”, is still useful for a friendly message, but it cannot be the guarantee: two requests from the same member, such as a double click, can both run the check before either saves, both see nothing, and both insert. The index is checked as each row is stored, so the second insert is refused however the requests interleave, and the view turns the refusal into a clear result. In Django this becomes a UniqueConstraint with a condition, in Chapter 21.

Behind the scenes:

request A: count active rows -> 0
request B: count active rows -> 0
request A: insert -> stored
request B: insert -> stored, or refused by the index

Code proof: the same interleaving, first without the index, then with it:

import sqlite3

TABLE = """CREATE TABLE registration (
    event_id INTEGER, member_id INTEGER, status TEXT)"""
INDEX = """CREATE UNIQUE INDEX one_active
    ON registration (event_id, member_id)
    WHERE status = 'active'"""
CHECK = """SELECT COUNT(*) FROM registration
    WHERE event_id = 7 AND member_id = 1
    AND status = 'active'"""
ADD = "INSERT INTO registration VALUES (7, 1, 'active')"

for label, schema in [("no index", [TABLE]),
                      ("index", [TABLE, INDEX])]:
    db = sqlite3.connect(":memory:", autocommit=True)
    for sql in schema:
        db.execute(sql)
    seen = [db.execute(CHECK).fetchone()[0] for _ in "AB"]
    try:
        db.execute(ADD)
        db.execute(ADD)
        result = "both stored"
    except sqlite3.IntegrityError:
        result = "second refused"
    print(f"{label}: checks saw {seen}, {result}")
no index: checks saw [0, 0], both stored
index: checks saw [0, 0], second refused

The proof plays both requests on one connection, in the order a real overlap can take; Chapter 33 tests true concurrency on PostgreSQL.

Common mistakes:

  • Relying on a check in the view as the only protection.
  • Using a full unique pair, which blocks registering again.
  • Letting the refusal surface as an error page instead of a message.

Follow-up the interviewer might ask:

  • “Would the same index protect capacity? Why not?”
  • “How would you tell a duplicate from other integrity errors in the view?”

L4 (Staff): Should Otahque store a count of places taken, or derive it? Where does each rule about capacity live?

What the interviewer is testing: Looking ahead: can you weigh one source of truth against read cost, and name what actually enforces an invariant?

Flip to check your answerFold answer back
Name the invariant: active registrations never exceed capacity. Derive the count from registrations. A stored counter would be a second copy. Enforce the invariant by locking and rechecking in one transaction. Measure before adding a counter.
Figure 15.7 — Capacity: one source of truth, enforced in a transaction.

Perfect answer: Start from the invariant: active registrations for an event never exceed its capacity. Store the capacity, which is a decision, and derive the count, which is a consequence; counting active registrations for one event is cheap with an index. A stored counter is a second copy of the same fact. Every registration, cancellation, import, and correction must update it in the same transaction, and any path that forgets makes it drift, which is why systems that keep counters also run reconciliation jobs. Neither choice enforces the invariant on its own: two requests can both see one free place. Enforcement belongs in a transaction that locks the event row, recounts, and inserts, which Chapter 33 builds on PostgreSQL. A counter becomes worth its cost only when measurements show that counting is the bottleneck, and then it is a cache of the derived value, not the authority.

Behind the scenes:

stored: event.capacity          the decision
derived: count of active rows   the consequence
counter: a copy that can drift  only after measuring
enforce: lock, recount, insert  one transaction

Code proof: one path forgets the counter, and the copy disagrees with the count:

import sqlite3

db = sqlite3.connect(":memory:", autocommit=True)
db.execute("""CREATE TABLE event (
    id INTEGER PRIMARY KEY, capacity INTEGER,
    taken INTEGER)""")
db.execute("""CREATE TABLE registration (
    event_id INTEGER, status TEXT)""")
db.execute("INSERT INTO event VALUES (7, 2, 0)")
for keeps_counter in (True, False):
    db.execute("INSERT INTO registration"
               " VALUES (7, 'active')")
    if keeps_counter:
        db.execute("UPDATE event SET taken = taken + 1")
stored = db.execute("SELECT taken FROM event").fetchone()[0]
counted = db.execute("""SELECT COUNT(*) FROM registration
    WHERE status = 'active'""").fetchone()[0]
print(f"stored counter: {stored}, derived count: {counted}")
stored counter: 1, derived count: 2

Common mistakes:

  • Treating a counter column as the authority and trusting it.
  • Believing a CHECK constraint can compare a count across rows.
  • Adding a counter for speed without a measurement.

Follow-up the interviewer might ask:

  • “If you did add a counter, how would you detect and repair drift?”
  • “What changes when capacity is reduced below the current count?”

L5 (Lead): How should the ERD evolve as waitlists, attendance, and several communities arrive, without breaking existing records?

What the interviewer is testing: Looking ahead: can you lead schema change as a reviewed decision, protect existing data, and keep different facts in different places?

Flip to check your answerFold answer back
Change the ERD first, with a reason. Check every rule and query it affects. New columns start empty or with a default. Migrate, and move existing data. Review, test, and record the decision.
Figure 15.8 — Evolving the data model without breaking records.

Perfect answer: Treat the ERD as the place where a data change is proposed and reviewed before any migration exists. Each new capability gets the smallest structure its rules need, and different facts stay separate: a waitlist position is not a registration status, and attendance is its own record with its own actor and time, because a registration does not prove anyone came. Several communities change the meaning of every uniqueness rule, which then holds within a community, so that change is designed in Chapters 67 and 68, not slipped in. For the change itself, existing rows constrain what is possible: a new column must start empty or with a default, and data is moved by a migration that can be tested on a copy. As lead, I make sure each change has a reason, an owner, updated rules and open questions in the ERD, tests for the rules it touches, and a record of the decision.

Behind the scenes:

propose in the ERD -> review the rules it touches
add new columns empty, or with a default
migrate and move existing data -> test on a copy
record the decision and its reason

Code proof: existing rows decide which new column can be added:

import sqlite3

db = sqlite3.connect(":memory:", autocommit=True)
db.execute("CREATE TABLE registration"
           " (id INTEGER, status TEXT)")
db.execute("INSERT INTO registration VALUES (1, 'active')")
changes = [
    "ALTER TABLE registration ADD COLUMN attended_at TEXT",
    "ALTER TABLE registration ADD COLUMN source"
    " TEXT NOT NULL",
]
for sql in changes:
    column = sql.split()[5]
    try:
        db.execute(sql)
        print("added:", column)
    except sqlite3.OperationalError as error:
        print("refused:", error)
print(db.execute("SELECT * FROM registration").fetchall())
added: attended_at
refused: Cannot add a NOT NULL column with default value NULL
[(1, 'active', None)]

The first change is allowed because the existing row can hold an empty value. The second is refused because the existing row would break NOT NULL. Chapter 18 shows how Django’s migrations handle both cases, including data migrations. The attended_at column shows the mechanics only: the design keeps attendance in a record of its own.

Common mistakes:

  • Changing the schema first and the documented design afterwards, or never.
  • Folding attendance or waitlist position into the registration status.
  • Adding a required column to a table that already holds data, without a default or a data step.

Follow-up the interviewer might ask:

  • “How would uniqueness rules change when there are several communities?”
  • “Who should approve a change to the data model, and what evidence should they see?”

Next: Chapter 16 turns this ERD into Django models and fields, starting with the event.

PAGE 006