Chapter 16 · Django models and field choicesCHAPTER 16
Complete six-part pre-release for review. The model is a proposal; no database table or migration is 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 SIXTEEN
Django models and field choices
Stage 3: Data and the database (Chapters 15 to 23)
Prerequisites: Chapters 2 and 7 to 15, including the Chapter 15 project, its 18 passing tests, its empty db.sqlite3, and the proposed ERD in docs/design/erd.md
What you’ll build: a Django model for Otahque’s events, with chosen field types, a fixed list of statuses that starts at Draft, and two tests that run without creating a database table.
Why This Matters
Chapter 15 ended with a drawing. Its EVENT box lists what Otahque records about an event: a title, when it starts, its time zone, a location, a capacity, and a status. Sam reads it and asks practical questions. When he enters an event, how long may its title be? What does he write as the location of an online meetup? Can members see a new event as soon as he saves it? The diagram says “text title” and “a status from a fixed list”, which was enough to agree on a design. It is not enough to answer Sam. Each answer is a choice that someone has to make and write down in a place the program can use.
In Django, that place is a model: a Python class that describes one kind of record, one field at a time. Each field says what kind of value it holds, such as text, a moment in time, or a whole number, and which limits apply. Django reads this single description for many jobs. In later chapters it creates the table from it (Chapter 18), saves and fetches records through it (Chapter 19), builds an editing screen from it in the admin (Chapter 23), and makes form fields from it (Chapter 24). Because every one of those parts reads the same class, they cannot disagree about what an event is. That is Chapter 15’s rule of one fact in one place, applied to the program itself.
This chapter answers Sam’s questions as field choices. A title holds at most 200 characters. Every event has a location, and an online event records Virtual. A new event starts as a draft, the status that Chapter 2’s rules keep hidden from members until it is published. You will see what each choice allows and what it does not yet guarantee, and you will prove the model’s behaviour with tests before any record exists.
By the end of the chapter, you will be able to:
explain what a Django model is and how its fields relate to the columns of a table;
choose field types and options for an event’s title, start time, time zone, location, capacity, and status, and say what each choice allows;
tell blank from null, and say what a field’s list of choices checks and what it leaves unchecked;
declare Otahque’s event statuses as a fixed list with TextChoices, starting at Draft;
give a model a readable name and a default order with __str__() and Meta;
check the model with Django’s system check and two tests that need no database.
The model is a proposal, like the ERD it comes from. This chapter writes only the Event model and creates no table and no migration. The member model waits for Chapter 17, because Django’s command that creates tables would also create its built-in user table, and the user model has to be chosen first. Chapter 18 then creates the tables. Relationships between events, members, and registrations arrive in Chapter 20. Some rules the ERD records are not yet enforced: a capacity of zero, a status outside the list, or a time-zone name that does not exist would all reach the database unchecked until Chapter 21 adds validation and constraints. The event pages keep showing their sample events until Chapter 19 reads real records. A location is free text, so Virtual is a convention organizers follow, not a value the model checks; whether Otahque needs a separate setting for online and in-person events remains an open product question.
Chapter 15 described an event as an entity with attributes. Django describes the same thing as a Python class, and the class is what the rest of Django reads.
New Concept: a Django model
What problem exists? Many parts of a program need the same facts about one kind of record: which values it has, what type each value is, and which limits apply. When each part keeps its own copy of those facts, the copies drift apart.
What did people do before? They wrote the table in SQL, then repeated its columns by hand in the code that saved records, in the forms that collected them, and in the pages that showed them.
What is a model? A Python class that inherits from django.db.models.Model. Each class attribute made from a field class, such as models.CharField, is a field: one value that every record of that kind has. One model usually matches one database table, each field one column, and each instance of the class one row.
Why use one? Django reads the class to create and change the table, to save and fetch rows, and to build admin screens and forms, so the description is written once.
Now let’s use it. The rest of this part reads a model before you write one in How We Build It.
Here is the start of the model this chapter builds, with one field. Read it; you will type the complete version in Step 3:
Python
from django.db import models
class Event(models.Model):
title = models.CharField(max_length=200)
models is Django’s module of model and field classes. Event inherits from models.Model, which is what makes it a model rather than an ordinary class. title is a field, and CharField says it holds text up to a maximum length. Django names the table after the app and the model, in lower case, joined by an underscore: events_event. It also adds a field you did not write. Every row needs the primary key that Chapter 15 described, so when no field declares one, Django adds id. Since Django 6.0, its type is BigAutoField: a whole number that the database assigns, counting up, with room for far more rows than Otahque will ever hold. The ERD’s int id PK is that number.
Figure 16.1 — The Event model beside the table Django can create from it.
The dashed zone in Figure 16.1 matters. The table does not exist yet, and writing the class does not create it. An instance does not create a row either: Event(title='Python meetup') makes an object in Python’s memory, and nothing reaches the database until code calls its save() method. This chapter never calls save(), because there is no table to save into until Chapter 18.
Field types: what kind of value
A field type says what kind of value a field holds, and so which column type the database uses for it. Table 16.1 lists the four types the Event model uses.
Table 16.1 — The field types the Event model uses
Field type
Holds
SQLite column
Event fields
CharField
Text up to a maximum length
varchar(n)
title, timezone, location, status
DateTimeField
A date with a time of day
datetime
starts_at, ends_at
PositiveIntegerField
A whole number, 0 or more
integer, CHECK ≥ 0
capacity
BigAutoField
A number the database assigns
integer, primary key
id, added by Django
Choose a type by what the value means, not by how it looks when typed. A capacity is a count, so it is a whole number that can be compared and added up. A start time could be typed as the text “19 Nov, 6.30pm”, but text cannot be sorted into time order or converted between time zones, so starts_at is a DateTimeField, and so is ends_at, the end time. For long text with no natural limit, such as a description, Django has TextField; the proposed Event has no such field yet.
Field options: limits, defaults, and empty values
New Concept: field options
What problem exists? A type says what kind of value a field holds, not which values are acceptable: how long it may be, whether it may be empty, and what a new record starts with.
What did people do before? They wrote checks by hand in each place that accepted input, and sooner or later one place was missed.
What are field options? Keyword arguments to the field class, such as max_length=200, default, blank, null, and choices. Each records one decision about the field’s values.
Why use them? Django turns each option into behaviour in the right places: a validation check, a column setting, or a form control.
Now let’s use it. Each option below comes with what it checks and where.
max_length is the most characters a CharField accepts. Django adds a validator that refuses longer text when a record is checked, and forms limit what can be typed. SQLite writes the number into the column type but does not enforce it; PostgreSQL, which Otahque uses from Chapter 32, does. In Django 6.1, a CharField on SQLite or PostgreSQL may leave max_length out, which means no limit at all, so its absence is not an error. Otahque sets every limit on purpose: 200 characters for a title and a location, and 64 for a time-zone name, well above the longest names in use.
default is the value a new instance starts with when none is given, either a fixed value or a function that Django calls. It is applied in Python when the object is created, not by the database.
blank and null answer two different questions, and they are easy to confuse:
blank is about validation: may the value be empty when Django checks the record? It defaults to False, which makes the field required.
null is about storage: may the column hold NULL, the database’s marker for no value? It defaults to False, which makes the column NOT NULL.
For text, Django’s convention is that an empty value is the empty string, ''. An optional text field therefore uses blank=True alone. Adding null=True as well would give the field two different ways of being empty, '' and NULL, and every query would have to check for both. A date has no empty string, so an optional date needs both options: null=True, so that the column can hold no value, and blank=True, so that validation accepts none.
Every Event field keeps both defaults, so every field is required. That includes the location: an online event records Virtual instead of leaving it empty.
Try it yourself
Que. 1 Chapter 15’s REGISTRATION entity has registered_at, set when a member registers, and cancelled_at, which is empty until the registration is cancelled. Which field type suits each, and which options does cancelled_at need?
Flip to check your answerFold answer back
Answer. Both are moments in time, so both are DateTimeField. registered_at always has a value, so it keeps the defaults. cancelled_at must hold no value until a cancellation happens, and a date-time has no empty string, so it needs null=True for storage and blank=True for validation. Chapter 20 writes the Registration model.
Instants and time zones
starts_at and ends_at each hold an instant: one moment shared by everyone, whichever clock they read. The project’s settings, as Django generated them, contain USE_TZ = True and TIME_ZONE = 'UTC'. With USE_TZ on, Django expects aware datetimes, which carry their offset from Coordinated Universal Time (UTC), and converts them to UTC before storing them. A naive datetime, with no zone information, is ambiguous; Django warns when one is saved and assumes the default time zone. This read-only example creates one instant in Kolkata and prints it twice:
Both lines are the same instant. Storing only the instant loses something Sam needs: people deciding whether to attend a meetup in Kolkata expect to read 18:30, not 13:00. That is why the event also stores timezone, a name from the IANA time-zone database such as Asia/Kolkata or Europe/London, which Python’s zoneinfo module reads. To the model, the name is plain text: CharField(max_length=64) accepts Asia/Kolkata, and it also accepts a name that does not exist. Checking the name against the list in zoneinfo.available_timezones() is validation, which Chapter 21 adds.
A fixed list of statuses
New Concept: choices and TextChoices
What problem exists? A status must be one of a few agreed values. Free text would let “Draft”, “DRAFT”, and “drft” all appear, and every page would have to guess what each meant.
What did people do before? They scattered constants through the code, or repeated a list of pairs wherever a menu was needed.
What is TextChoices? A Django enumeration: a class whose members each pair a stored value, such as 'draft', with a reader-facing label, such as 'Draft'. Given to a field as its choices, it becomes the field’s list of allowed values.
Why use it? Values and labels live in one place, code can name Event.Status.DRAFT instead of typing a string, and Django uses the list for validation, forms, and the admin.
Now let’s use it. Here is Otahque’s list, as it will sit inside the Event model.
Python
class Status(models.TextChoices):
DRAFT = 'draft', 'Draft'
PUBLISHED = 'published', 'Published'
CANCELLED = 'cancelled', 'Cancelled'
status = models.CharField(
max_length=20,
choices=Status,
default=Status.DRAFT,
)
In each member, the first string is the stored value and the second is the label. Members are strings, so Event.Status.DRAFT == 'draft' is true. Event.Status.values lists the values and Event.Status.labels the labels, and Django gives every Event a get_status_display() method that returns the label for its current status. The longest value has nine characters; max_length=20 leaves room for a value added later. The default answers Sam’s third question: a new event starts as a draft, and stays hidden from members until it is published.
A list of choices is not a guarantee by itself. Table 16.2 shows which rules about an event are checked now, and by what.
Table 16.2 — What checks each Event rule in this chapter
Rule
full_clean() and forms
The database
Title at most 200 characters
Yes
Not on SQLite; yes on PostgreSQL
Status from the list
Yes
No
Every field has a value
Yes (blank=False)
Yes (NOT NULL)
Capacity not negative
Yes
Yes (CHECK capacity ≥ 0)
Capacity more than 0
No: Chapter 21
No: Chapter 21
Time zone is a real name
No: Chapter 21
No
full_clean() is a method every model instance has. It runs all the field checks and raises ValidationError, listing each field’s problems. Django’s forms call it, so data typed into a form is checked. Calling save() does not call it, though: code that saves directly can store a status outside the list, because the database has no rule about it. Chapter 21 adds database constraints, so that the database refuses such rows whichever code saves them.
A readable name and a default order
A model can also have methods and settings for the whole record. The __str__() method returns the text Python shows for an object. Django uses it in the shell, in admin lists, and in error messages, so it should name the record in words a person recognizes. Without one, every event appears as Event object (None); with one that returns the title, it appears as Python meetup.
A nested class named Meta holds options about the model as a whole rather than one field. ordering = ['starts_at'] makes every query for events return the earliest first, unless that query asks for a different order; '-starts_at' would reverse it. Ordering has a cost: the database sorts on every query that uses it, even where the order does not matter. For Otahque’s event lists, date order is nearly always wanted, so the model keeps it, and Chapter 22 shows how a single query chooses its own order. Later chapters add other Meta options, such as database constraints in Chapter 21.
Under the Hood: what happens when Django imports a model
When Django starts, django.setup() loads the settings and imports the models module of each app in INSTALLED_APPS. Python runs the class Event statement, and Django’s model machinery takes over: it collects each field, gives it its name and column, adds the id field, applies Meta, and stores the result as Event._meta, the model’s metadata. It then registers the model in the app registry, Django’s index of installed apps and their models, as events.Event. None of this touches the database. Creating the table is a separate, deliberate step: makemigrations compares the models with the project’s migration files and writes a new file describing the difference, and migrate applies it to the database. Chapter 18 does both. Because models need the registry, importing one before setup has finished fails with AppRegistryNotReady and the message “Apps aren’t loaded yet.”
You will look at Event._meta yourself in Step 4, through a small script that calls django.setup() first. _meta starts with an underscore, which in Python usually means “private”, but Django documents it as the Model _meta API, a supported way to inspect any model.
In practice: renaming a status
Situation. Later, Sam asks for cancelled events to say “Called off” instead of “Cancelled”, and a developer suggests changing the stored value to match.
Application. The label can change freely: it lives only in the code, and every page that calls get_status_display() shows the new words. The stored value 'cancelled' is written in every cancelled event’s row, in the tests, and in any export a partner reads, so changing it needs a data migration (Chapter 18) and a search for every comparison with the old value.
Consideration. Treat stored values as identifiers: short, lower case, and stable. Labels are for people and may later be translated; values are for the program.
Start from Chapter 15, in the folder containing manage.py, with your own .env, the locked environment, 18 passing tests, docs/design/erd.md committed, and a db.sqlite3 with no tables. You change two files: events/tests.py, where two tests are written first, and events/models.py, which receives the Event model. Views, templates, and the sample events stay as they are; the pages read real events from Chapter 19. One practice script goes in the practice folder beside the project, as in Chapter 15. At the end, 20 tests pass, Django loads the model, and the database still has no tables.
The Custom Way
This illustration shows the table written by hand in SQL; do not add it to the project:
illustration_only/event_table.sql (not part of the project)
CREATE TABLE event (
id INTEGER PRIMARY KEY,
title VARCHAR(200) NOT NULL,
starts_at TEXT NOT NULL,
ends_at TEXT NOT NULL,
timezone VARCHAR(64) NOT NULL,
location VARCHAR(200) NOT NULL,
capacity INTEGER NOT NULL CHECK (capacity >= 0),
status VARCHAR(20) NOT NULL DEFAULT 'draft'
);
SQLite would accept it, and it is close to what Django will generate. But it is only the table. The Python code that saves an event must list the same eight columns with the same spelling. The statuses and their labels live somewhere else again, and every form must repeat the length limits. When a column changes, each copy must change with it, by hand and in step with the database, and nothing checks that the copies agree. The Django way writes the description once, in Python, and derives the table, the validation, and later the forms from it.
The Django Way
Four steps build the model. The tests come first, so you see them fail before the model exists.
Step 1: Check the starting point
Run the Chapter 15 tests beside manage.py, in PowerShell, a macOS shell, or Linux/WSL Bash:
Terminal
uv run python manage.py test events
Expected result, shortened with ... where lines are left out:
Output
Found 18 test(s).
System check identified no issues (0 silenced).
..................
...
Ran 18 tests in ...
OK
Then confirm that the database has no tables, with the query from Chapter 15. In PowerShell, beside manage.py:
PowerShell
uv run python -m sqlite3 db.sqlite3 `
"SELECT name FROM sqlite_schema"
In a macOS shell or Linux/WSL Bash, beside manage.py:
Terminal
uv run python -m sqlite3 db.sqlite3 \
"SELECT name FROM sqlite_schema"
Expected result: nothing at all. If the query lists tables, migrate has been run; follow Chapter 15’s recovery and rename the file, for example to db-before-ch16.sqlite3, keeping it until Chapter 17 confirms that nothing in it is needed. Finally, run git status --short; it should print nothing, because Chapter 15’s work is committed. If it lists files, commit or put aside that work before you begin, so that this chapter’s commit holds only its own changes.
Step 2: Write the tests first
The tests say what the model must do before the model exists. Open events/tests.py. Three import lines are new: the first, the ValidationError line, and the last. Make the imports at the top of the file match this listing:
events/tests.py (imports at the top)
from datetime import UTC, datetime
from pathlib import Path
from unittest.mock import patch
from django.contrib.staticfiles import finders
from django.core.exceptions import ValidationError
from django.template import Context, Template
from django.template.loader import render_to_string
from django.test import SimpleTestCase
from django.urls import resolve, reverse
from . import views
from .models import Event
UTC is Python’s own UTC time zone, so the test’s start time is an aware datetime. Then add a new test class at the end of the file:
events/tests.py (end of the file)
class EventModelTests(SimpleTestCase):
"""The Event model's rules, checked without a database."""
def make_event(self, **changes):
"""Make a valid unsaved event with these changes."""
fields = {
'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': 'Virtual',
'capacity': 40,
}
fields.update(changes)
return Event(**fields)
def test_str_is_title(self):
event = self.make_event()
self.assertEqual(str(event), 'Python meetup')
def test_status_starts_draft_and_is_checked(self):
event = self.make_event()
self.assertEqual(event.status, Event.Status.DRAFT)
event.full_clean()
event.status = 'archived'
with self.assertRaises(ValidationError) as caught:
event.full_clean()
self.assertEqual(
caught.exception.message_dict,
{'status': [
"Value 'archived' is not a valid choice."
]},
)
make_event() is a helper, not a test, because its name does not start with test. It builds a complete, unsaved event, and **changes lets a test replace any of its values. The first test checks the readable name. The second checks three things in order: a new event starts as a draft; the complete event passes full_clean(), which proves that the next error comes from the status alone; and a status outside the list is refused with exactly one message, for the status field. SimpleTestCase, which the earlier tests also use, refuses any database query, so these tests prove that nothing here needs a table.
Common Error: saving in a SimpleTestCase
Adding event.save() to one of these tests looks harmless, but saving is a database query. The test fails with DatabaseOperationForbidden and a message that begins “Database queries to ’default’ are not allowed in SimpleTestCase subclasses.” Remove the call: there is no table to save into yet. Tests that save records begin once Chapter 18 has created the tables.
Run the tests:
Terminal
uv run python manage.py test events
Expected result, shortened with ... where lines are left out:
Output
Found 1 test(s).
System check identified no issues (0 silenced).
E
...
ImportError: Failed to import test module: events.tests
...
from .models import Event
ImportError: cannot import name 'Event' from ...
...
FAILED (errors=1)
This is the red stage, and it looks worse than it is. Python could not import events/tests.py at all, because events/models.py has no Event yet, so Django reports the whole file as one failed “test”. The 18 earlier tests did not run, because they live in the same file; they will return in the next step. The last ImportError line goes on to name events.models and the full path of its file.
Step 3: Write the Event model
Replace the contents of events/models.py, which still holds only the comment that startapp generated, with this listing:
events/models.py
"""Models for Otahque's events."""
from django.db import models
class Event(models.Model):
"""A proposed Otahque event, from the Chapter 15 ERD."""
class Status(models.TextChoices):
"""Where an event is: draft, published, or cancelled."""
DRAFT = 'draft', 'Draft'
PUBLISHED = 'published', 'Published'
CANCELLED = 'cancelled', 'Cancelled'
title = models.CharField(max_length=200)
starts_at = models.DateTimeField()
ends_at = models.DateTimeField()
timezone = models.CharField(max_length=64)
location = models.CharField(max_length=200)
capacity = models.PositiveIntegerField()
status = models.CharField(
max_length=20,
choices=Status,
default=Status.DRAFT,
)
class Meta:
ordering = ['starts_at']
def __str__(self):
return self.title
Every line comes from What You Need to Know: the statuses nested inside the model, so code names them Event.Status; seven fields in the order of the ERD; Meta with the default order; and __str__(). The docstring records where the design came from. Field class names are case-sensitive, and a misspelling stops Django before any test runs.
Common Error: a misspelled field class
Writing models.Charfield instead of models.CharField stops every command with an AttributeError. Its message says that django.db.models has no attribute Charfield and ends Did you mean: 'CharField'?, after a traceback that names the line with the misspelling. Python’s suggestion is usually right; correct the spelling on that line and run the command again.
Run the tests again:
Terminal
uv run python manage.py test events
Expected result, shortened with ...:
Output
Found 20 test(s).
System check identified no issues (0 silenced).
....................
...
Ran 20 tests in ...
OK
The 18 earlier tests are back, and the two new ones pass. Then run Django’s system check, which loads every model and reports problems with fields and options:
Terminal
uv run python manage.py check
Output
System check identified no issues (0 silenced).
Step 4: Inspect the model without the database
manage.py shell starts Python with Django set up, and -c runs one line of Python and exits. The shell imports every model automatically and says how many objects it imported, so Event needs no import:
Terminal
uv run python manage.py shell -c "print(Event.Status.values)"
If you write your own -c commands, put any quotation marks inside the Python in single quotes, so that the same command works in PowerShell and in a macOS shell or Linux/WSL Bash. For a longer look, use a script. A script run with uv run python is not set up for Django, so it needs a helper that loads the settings first. If you have no practice folder from Chapter 15, create it with mkdir ../practice, the same command in every shell. Then create the helper:
../practice/setup_django.py
"""Load Otahque's settings so a practice script can use them.
Run practice scripts from the folder that holds manage.py.
"""
import os
import sys
import django
sys.path.insert(0, os.getcwd())
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'config.settings'
)
django.setup()
The helper puts the current folder, the one holding manage.py, on Python’s import path, names the settings module, and calls django.setup(), which builds the app registry described in Under the Hood. Now create the script that uses it:
../practice/inspect_event.py
import setup_django # loads Otahque's settings first
from events.models import Event
print(Event._meta.db_table)
for field in Event._meta.fields:
print(field.name, field.get_internal_type())
print(Event.Status.values)
print(Event._meta.ordering)
Run it from the folder that holds manage.py, in any of the three shells:
Terminal
uv run python ../practice/inspect_event.py
Output
events_event
id BigAutoField
title CharField
starts_at DateTimeField
ends_at DateTimeField
timezone CharField
location CharField
capacity PositiveIntegerField
status CharField
['draft', 'published', 'cancelled']
['starts_at']
The table name, the added id, every field type, the statuses, and the order all come from the class, and none of it needed a table. Run the Step 1 query again: it still prints nothing. Then check what changed:
Terminal
git status --short
Output
M events/models.py
M events/tests.py
M in the second column marks a file changed but not yet staged. Nothing appears under events/migrations/, and the practice folder is outside the project, so Git does not see it.
Common Error: making a migration to see the table
Running Django’s makemigrations command now would write events/migrations/0001_initial.py, a migration file describing the table, and migrate would then create Django’s built-in tables, including the user table that Chapter 17 must choose first. If either has happened, keep what was made: move the new migration file into ../practice and rename db.sqlite3 as in Step 1, so that Chapter 18 starts from no migration and no tables. Do not delete them in this chapter.
When something goes wrong
Table 16.3 — Model problems and safe recovery
Symptom
Likely cause
Safe recovery
ImportError: cannot import name 'Event' from events.models
Step 3 not done yet, or the class name misspelled
Write the model, or compare the class line with the listing
AttributeError: ... has no attribute 'Charfield'
A field class misspelled
Use the spelling Python suggests, on the line the traceback names
(fields.E121) 'max_length' must be a positive integer.
max_length is 0 or not a whole number
Use the number in the listing
AssertionError: '' != Event.Status.DRAFT
default=Status.DRAFT left out
Add the default to the status field
ValidationError: {'location': [...]} in the status test
make_event() is missing a value or has a typo
Compare the helper's dictionary with the listing
DatabaseOperationForbidden
A test calls save() or queries the database
Remove the call; saving waits until Chapter 18
ModuleNotFoundError: No module named 'events'
A practice script imported the model before setup_django
Put import setup_django on the first line
can't open file ... inspect_event.py
The command was run from another folder
Run it from the folder that holds manage.py
events/migrations/0001_initial.py appears
makemigrations was run
Move the file into ../practice; Chapter 18 makes its own
Work through Table 16.4 from the folder that holds manage.py. The test rows check behaviour; the inspection rows check the model’s metadata; the last rows check that nothing outside the two files changed.
Table 16.4 — Verification checklist for Chapter 16
Check
Command or action
Expected result
Red stage seen
The Step 2 run, before the model
ImportError, FAILED (errors=1)
Tests pass
uv run python manage.py test events
Found 20 test(s), OK
Model loads
uv run python manage.py check
No issues (0 silenced)
Statuses fixed
The Step 4 shell command
['draft', 'published', 'cancelled']
Metadata
uv run python ../practice/inspect_event.py
events_event, eight fields, ['starts_at']
Primary key
The second line of that output
id BigAutoField
No tables yet
The Step 1 query
No output
Only two files changed
git status --short
M events/models.py and M events/tests.py; no migration
Que. 2 You saved events/models.py, and Django loads the Event model. Does the project now have an event table?
Flip to check your answerFold answer back
Answer. No. Importing the model builds its metadata and registers it with the app registry, without touching the database. A table is created only when a migration is written with makemigrations and applied with migrate, which Chapter 18 does.
Que. 3 An event title has 250 characters. Where is it refused?
Flip to check your answerFold answer back
Answer. By full_clean() and by forms, through the validator that max_length=200 adds. SQLite would store it anyway, because it does not enforce the length in varchar(200); PostgreSQL would refuse it.
Que. 4 Why does the status field have default=Status.DRAFT?
Flip to check your answerFold answer back
Answer. So that every new event starts as a draft, which Chapter 2’s rules keep hidden from members. An organizer must publish it deliberately. Without the default, a new event would start with an empty status, which is not in the list.
Que. 5 Code calls save() on an event whose status is 'archived'. Once tables exist, what stops it?
Flip to check your answerFold answer back
Answer. Nothing in this chapter. Choices are checked by full_clean() and forms, and save() does not call full_clean(). The database has no rule about the status column until Chapter 21 adds a constraint.
Que. 6 Why does location accept Virtual but not an empty value?
Flip to check your answerFold answer back
Answer. The field is required, because blank and null keep their defaults, so validation refuses an empty value and the column refuses NULL. Virtual is ordinary text: a convention organizers follow for online events, which the model does not check.
Mini-Challenge
Que. 7 Sam would like an optional one-line summary for each event, shown under its title. Write the field declaration you would propose, and explain whether it should use blank, null, or both. Write it in your notes, not in events/models.py: whether events have a summary is a product decision still to be made, and Chapter 17 starts from the model as it is now.
Flip to check your answerFold answer back
Answer. A summary is text, so the convention for optional text applies: blank=True, so validation accepts an empty summary, with an empty string as the default, and no null=True:
illustration_only/summary_field.py (not part of the project)
CharField with a limit suits a single line; TextField would suit a longer description. With null=True as well, an event could have no summary in two ways, '' and NULL, and every query looking for events without a summary would need to check for both. null=True is right when “no value yet” must be told apart from “empty”, as with Registration’s cancelled_at. Record the field as a proposal beside the ERD’s open questions until the product decision is made.
What We Learned
A Django model is a Python class that describes one kind of record; its fields usually become a table’s columns, and each instance is one row in waiting.
Django adds an id primary key, a BigAutoField, when no field declares one, and names the table after the app and the model.
A field type says what kind of value a field holds; options such as max_length, default, blank, null, and choices record which values are acceptable.
blank concerns validation and null concerns storage; optional text uses blank=True with the empty string, and optional dates need both.
TextChoices pairs stored values with labels; choices are checked by full_clean() and forms, not by save() or the database.
An aware DateTimeField stores the instant, and a separate time-zone name says how to show it.
Importing a model builds its metadata and registers it; it creates no table.
Key terms
Use Table 16.5 to explain this chapter’s ideas in your own words.
Table 16.5 — Key terms from Chapter 16
Term
Meaning
Model
A Python class inheriting from models.Model that describes one kind of record.
Field
A class attribute made from a field class; one value every record has.
Instance
One object of a model class; becomes a row when saved.
Field option
A keyword argument, such as max_length or default, that limits or shapes a field's values.
blank
Whether validation accepts an empty value.
null
Whether the database column may hold NULL.
Choices
A field's list of allowed values, each with a label.
TextChoices
A Django enumeration of text values and their labels.
full_clean()
The method that runs a model instance's validation checks.
BigAutoField
A database-assigned whole-number primary key; Django's default.
Aware datetime
A date and time that carries its offset from UTC.
Meta
A nested class holding options for the whole model, such as ordering.
App registry
Django's index of installed apps and their models, built at setup.
_meta
A model's metadata, inspected through Django's documented Model _meta API.
Readiness checkpoint: you are ready for Chapter 17 when all 20 tests pass, manage.py check reports no issues, inspect_event.py prints the output shown in Step 4, the Step 1 query still prints nothing, and the Event model and its tests are committed. Explain, in a sentence, why migrate must still wait. Return to the relevant step if any result is missing.
Git Commit
Stage the two changed files and check what is staged, in PowerShell, a macOS shell, or Linux/WSL Bash, beside manage.py:
Terminal
git add events/models.py events/tests.py
git status --short
Output
M events/models.py
M events/tests.py
M in the first column marks a change staged for the commit. Then record it:
Terminal
git commit -m "Add the proposed Event model and its tests"
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 what happens inside Django, which tests rarely show. 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 that starts by importing setup_django.py from Step 4; run it from the folder that holds manage.py with uv run python ../practice/ followed by the file name, in PowerShell, a macOS shell, or Linux/WSL Bash.
L1 (Junior): What does a Django model represent, and how does it relate to a database table?
What the interviewer is testing: Can you connect a class, its fields, and its instances to a table, its columns, and its rows?
Flip to check your answerFold answer back
Perfect answer: A model is a Python class, inheriting from models.Model, that describes one kind of record the application stores. Each field is a class attribute that says what kind of value every record has and which limits apply, and usually becomes one column. Each instance is one record in memory, and becomes a row when it is saved. Django creates the table from the model through migrations, adds an id primary key when none is declared, and uses the same class for queries, the admin, and forms, so the description of a record lives in one place.
Table 16.6 — A model and its table compared
In Django
In the database
Otahque example
Model class
Table
Event and events_event
Field
Column
title and its varchar(200) column
Instance
Row
Event(title='Python meetup')
Added id field
Primary key
id, a BigAutoField
Behind the scenes:
model (summary)
class Event(models.Model) -> table events_event
title = CharField(200) -> column title varchar(200)
no primary key declared -> Django adds id
Event(...) -> an object; a row after save()
Code proof: an instance exists in Python before any row does:
pk is None because only the database assigns a primary key, when a row is saved. The status already has its default.
Common mistakes:
Thinking that defining or importing a model creates its table.
Using one model for two kinds of record because they share a few fields.
Forgetting that Django adds the primary key, then declaring a second one by accident.
Follow-up the interviewer might ask:
“When would you declare your own primary key?”
“What does __str__() change, and where would you notice it?”
L2 (Mid-Level): How do blank and null differ, and when do you need each?
What the interviewer is testing: Can you separate validation from storage, and apply Django’s convention for empty text?
Flip to check your answerFold answer back
Figure 16.2 — blank checks values; null shapes the column.
Perfect answer:blank is a validation setting: it decides whether full_clean() and forms accept an empty value. null is a storage setting: it decides whether the database column may hold NULL. Both default to False, so a field is required twice over. For text, an empty value is the empty string, so an optional text field uses blank=True alone; adding null=True would give two kinds of empty that every query must handle. For types with no empty value, such as dates and numbers, an optional field needs null=True so the column can hold nothing, and blank=True so validation accepts nothing. A field such as cancelled_at, which is empty until something happens, is the typical case.
Behind the scenes:
blank and null (summary)
blank=False -> full_clean(): "This field cannot be blank."
null=False -> full_clean(): "This field cannot be null."
null=False -> the column is NOT NULL
optional text -> blank=True, default ''
optional date -> blank=True, null=True
Code proof: an empty title and missing start and end times fail for different reasons:
../practice/l2_blank_null.py
import setup_django
from django.core.exceptions import ValidationError
from events.models import Event
event = Event(title='', timezone='Europe/London',
location='Virtual', capacity=40)
try:
event.full_clean()
except ValidationError as error:
for name, messages in error.message_dict.items():
print(name, messages)
Output
title ['This field cannot be blank.']
starts_at ['This field cannot be null.']
ends_at ['This field cannot be null.']
The empty title fails the blank check. The missing times are None, Python’s value for nothing, which would become NULL in their columns, so each fails the null check.
Common mistakes:
Adding null=True to optional text fields out of habit.
Setting blank=True on a date without null=True, so validation accepts a value the column cannot store.
Believing blank changes the database.
Follow-up the interviewer might ask:
“How would you find every event without a summary if both '' and NULL were allowed?”
“What does a form do with a field that has blank=True?”
L3 (Senior): What happens when Django imports a model class, and what does not happen yet?
What the interviewer is testing: Do you understand the app registry and the boundary between model definitions and the database schema?
Flip to check your answerFold answer back
Figure 16.3 — Importing a model builds metadata, not a table.
Perfect answer: At start-up, django.setup() populates the app registry: it imports each installed app’s models module. Running the class statement hands the class to Django’s model machinery, which collects the fields, names their columns, adds a primary key if none is declared, applies Meta, and stores the result in _meta. The model is registered as events.Event, and other code can look it up by that label. Nothing touches the database: no table, column, or row is created, so a model can be loaded, inspected, and validated with no schema at all. The schema changes only through migrations, which compare the models with recorded migration files and apply the difference. That separation is why a model can be reviewed before it is frozen into a migration, and why importing models before setup has finished fails with AppRegistryNotReady.
Behind the scenes:
import (summary)
django.setup() -> import each app's models module
class Event -> fields collected, id added, _meta built
registry -> events.Event registered
database -> unchanged until makemigrations, migrate
Code proof: the registry knows the model, and the database has no tables:
../practice/l3_import.py
import setup_django
from django.apps import apps
from django.db import connection
from events.models import Event
print(apps.get_model('events', 'Event') is Event)
print(Event._meta.db_table)
print(connection.introspection.table_names())
Output
True
events_event
[]
table_names() asks the database for its tables and only reads; the empty list is Otahque’s real db.sqlite3.
Common mistakes:
Expecting a new field to appear in the database without a migration.
Importing models at the top of a module that runs before setup, such as a settings file.
Treating _meta as private and copying field lists by hand instead.
Follow-up the interviewer might ask:
“Why does apps.get_model() exist, rather than always importing the class?”
“What does makemigrations compare to decide what to write?”
L4 (Staff): Defend the Event field types, and say what the database does not yet guarantee.
What the interviewer is testing: Can you justify modelling choices and separate validation from guarantees, with a plan to close the gaps?
Flip to check your answerFold answer back
Figure 16.4 — What is checked now, and what waits for Chapter 21.
Perfect answer: Each type follows the meaning of the value. The title and location are bounded text, CharField with limits a reviewer can see. starts_at and ends_at are aware DateTimeFields, so each instant is stored once in UTC and compared correctly, and timezone keeps the IANA name that says how to show both, because neither can be derived from the other. Capacity is a count, so PositiveIntegerField, which also gives the database a CHECK that refuses negative numbers. Status is a short, stable value from TextChoices, defaulting to draft so that nothing is published by accident. The gaps are explicit: zero passes both checks, although the ERD requires more than zero; a time-zone name is not checked against the IANA list; nothing checks that an event ends after it starts; the status list is enforced only by full_clean(), which save() does not call; and SQLite does not enforce text lengths. I would close these in Chapter 21 with CheckConstraints for capacity, status, and the end time, and a validator for the time-zone name, each with a test that tries to save a bad row.
Behind the scenes:
guarantees (summary)
capacity -1 -> full_clean() and CHECK refuse
capacity 0 -> accepted: ERD says more than 0
status 'archived' -> full_clean() refuses; save() stores
timezone 'Mars/..' -> accepted: no check yet
ends before start -> accepted: no check yet
Code proof: an event with a capacity of 0, an invented time zone, and an end before its start passes every current check:
Storing a start time as text, or as a naive datetime with no zone.
Treating choices as a database guarantee.
Choosing PositiveIntegerField and assuming it means more than zero.
Follow-up the interviewer might ask:
“Why not store the start time in the event’s own time zone instead of UTC?”
“How would you validate the time-zone name, and where?”
L5 (Lead): Why must migrate wait until the custom user model is chosen?
What the interviewer is testing: Can you sequence decisions that are cheap now and expensive later, and explain the risk to a team?
Flip to check your answerFold answer back
Figure 16.5 — Choosing the user model before the first migrate.
Perfect answer: The AUTH_USER_MODEL setting names the model that represents users, and today it is Django’s built-in auth.User. Running migrate applies the built-in apps’ migrations, which create that model’s table, auth_user, and tables in other apps that refer to it. Django’s documentation says a new project can set up a custom user model before creating migrations or running migrate for the first time. Changing AUTH_USER_MODEL once those tables exist is not supported by an ordinary migration: the foreign keys and existing rows would all have to be moved. Otahque’s members are its users, and the ERD gives each member a unique email address and a display name, so the choice is real. As lead, I would make it a recorded decision before the first migrate, keep schema work behind it, and add a check that the database has no tables until then. The cost of waiting is small; the cost of changing later grows with every row.
Behind the scenes:
user model (summary)
AUTH_USER_MODEL = 'auth.User' (the default)
migrate -> auth_user, and tables that refer to it
change later -> move keys and rows by hand
Chapter 17 -> choose it; Chapter 18 -> migrate
Code proof: the default user model is named, and its table does not exist yet:
../practice/l5_user.py
import setup_django
from django.apps import apps
from django.conf import settings
from django.db import connection
print(settings.AUTH_USER_MODEL)
user_model = apps.get_model(settings.AUTH_USER_MODEL)
print(user_model._meta.db_table)
print(connection.introspection.table_names())
Output
auth.User
auth_user
[]
Common mistakes:
Running migrate early “just to get a database”.
Assuming a later data migration can swap the user model cheaply.
Leaving the decision undocumented, so a new teammate runs migrate first.
Follow-up the interviewer might ask:
“If a project has already migrated with the default user, what are the options?”
“Which fields would Otahque’s user model need first?”
Next: Chapter 17 chooses Otahque’s user model, before Chapter 18 creates the first tables.