CHAPTER TWENTY-ONE
Complete six-part pre-release for review. Public pages are unchanged; forms that show these messages to members arrive in Chapters 24 and 25.
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
Why This Matters
Chapter 20 ended with a warning. Nothing stops Sai from holding two active places at Sam’s Python meetup, and nothing stops a registration from being marked cancelled with no cancellation time. Both can happen without anyone meaning harm. Sai double-clicks the register button, and two requests arrive together. A script that cancels Raj’s place sets the status and forgets the time. An organizer types a capacity of 0, or the time-zone name Europe/Londn. Each mistake becomes a row, and every page, count, and email that reads that row afterwards is wrong.
Chapters 15 and 16 wrote these rules down: one active registration per member and event, a cancellation time exactly when a registration is cancelled, a capacity above zero, and a status from a fixed list. Chapter 17 left one more question open for this chapter, before anyone can sign up: are Sai@Example.org and sai@example.org the same member? So far the rules live only in documents. This chapter moves them into the project, at two levels. Validation is Python code that checks a row and explains what is wrong, when your code asks it to. A database constraint is a rule stored in the table itself, which the database applies to every write, whichever code sends it: a form, the shell, the admin site, an import script, or a future API.
By the end of the chapter, you will be able to:
- explain why
save()stores a row without validating it, and whatfull_clean()checks, in which order; - choose between a field validator,
Model.clean(), and a database constraint for a rule described in words; - write
CheckConstraintand conditionalUniqueConstraintrules, with stable names and messages people can read; - find the rows that would make a constraint migration fail, and fix them without losing work;
- test that the database refuses a bad row, and that validation explains why;
- explain why only the database can stop the second of two registrations that arrive together.
Forms, which call validation for a person typing into a page, are Chapters 24 and 25. The publication workflow, including what an event needs before it is published, is Chapter 26, and signing in is Chapter 27. The rule that an event never has more active places than its capacity needs transactions, and waits for Chapter 33. Rules that only PostgreSQL can express are Chapter 55.
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 001What You Need to Know
Three places a rule can live
Chapter 16 met validation once: full_clean() refused the status 'archived' because it is not one of the field’s choices. Chapter 19 then saved exactly that row with save(), and the database stored it. Both results were correct, and the difference between them is the subject of this chapter.
New Concept: validation and database constraints
What problem exists? A rule such as “capacity is more than 0” must hold for every event, however the row is written. Rows reach the table through forms, the shell, the admin site, scripts, and bulk operations that never create a model object.
What did people do before? They checked values in each place that wrote rows, with if statements before saving. Each new way of writing data needed the same checks again, and the one that forgot let bad rows in.
What are they? Validation is Python code that inspects an object before it is saved and raises ValidationError with messages. Django has three kinds: a validator on a field checks one value; Model.clean() checks several fields of one row together; and full_clean() runs them all. A database constraint is a rule written into the table’s definition, such as CHECK ("capacity" > 0). The database refuses any INSERT or UPDATE that breaks it, and Django raises IntegrityError.
Why both? Validation runs only when code calls it, but it can explain a problem to a person. A constraint runs on every write, but its error is meant for programmers. Otahque uses constraints as the guarantee and validation as the explanation.
Now let’s use it. Step 2 shows a row that passes full_clean() and is saved anyway, and Steps 4 to 7 close each gap.
Table 21.1 compares the three places. The first two are Python; the third is the database.
| Place | Runs when | Otahque example |
|---|---|---|
| Field validator | full_clean() is called | The time zone is a real name |
| Model.clean() | full_clean() is called | Fields that must agree in one row |
| Database constraint | Every INSERT and UPDATE | Capacity is more than 0 |
What full_clean() runs, and what save() does not
full_clean() runs four stages, in this order, and collects every error before it raises one ValidationError:
clean_fields()checks each field: required values,max_length,choices, and the field’s validators;clean()checks the row as a whole, and may also tidy values, such as lower-casing an email;validate_unique()checksunique=Truefields, such as the member’s email, by asking the database;validate_constraints()checks the rules in the model’sMeta.constraints, also by asking the database.
save() runs none of them. Django’s documentation states it plainly: full_clean() is not called automatically when you call save(). Querysets go further: update() and bulk_create() write rows without calling save() at all. Forms, from Chapter 24, call full_clean() for you; most other code does not.
Under the Hood: why save() does not validate
Validation can be expensive. validate_unique() and validate_constraints() each run database queries, and a validator such as this chapter’s time-zone check reads a list of about six hundred names. Code that saves thousands of rows from a trusted source, or saves one field after changing it, would pay that cost on every call. So Django leaves the decision to the caller: forms and the admin site validate, because people type into them, and other code calls full_clean() when it needs to. A side effect is that a rule enforced only by validation is enforced only where someone remembered to call it. That is why each Otahque rule that the database can express also becomes a constraint. Constraints joined model validation in Django 4.1: since then, full_clean() asks the database whether a row would break any rule in Meta.constraints, so the same rule produces a friendly ValidationError before saving and a hard IntegrityError if someone saves without asking. Older articles that say constraints are never part of full_clean() describe Django before 4.1.
A model’s clean() method is where a rule about several fields goes when it cannot, or should not, be a constraint. This example is for reading only; Otahque does not need it yet. It raises an error attached to a field by passing a dictionary:
def clean(self):
if self.status == 'published' and not self.location:
raise ValidationError(
{'location': 'A published event needs a place.'}
)Try it yourself
Que. 1 Chapter 19 saved an event with a capacity of 0 and the status 'archived'. Which of the two would full_clean() have refused at that point, and why did save() accept both?
Flip to check your answerFold answer back
Answer. Only the status. clean_fields() checks choices, so 'archived' fails, but a capacity of 0 is a valid PositiveIntegerField value, because that field allows zero. save() accepted both because it does not call full_clean(), and the table had no rule about either column yet.
Database constraints in Django
Django writes a constraint for you from a line in the model’s Meta class, and makemigrations turns it into SQL.
New Tool: CheckConstraint and UniqueConstraint
What problem exists? Rules must reach the table’s definition, and change with the models, through migrations like everything else in the schema.
What did people do before? They wrote ALTER TABLE ... ADD CONSTRAINT in SQL by hand, outside the project’s migrations, so the rules and the models could drift apart.
What are they? Two classes listed in Meta.constraints. models.CheckConstraint(condition=..., name=...) becomes a CHECK: every row must satisfy the condition. models.UniqueConstraint(fields=[...], name=...) makes a combination of columns unique. Given a condition= as well, it is conditional: the uniqueness applies only to rows that match the condition, which is exactly “at most one active registration per member and event”. Each constraint needs a name, unique in the database, and may have a violation_error_message, the text full_clean() shows.
Why use them? The rule lives beside the fields it protects, makemigrations writes the SQL, sqlmigrate shows it, and full_clean() can check it before saving.
Now let’s use it. Steps 4 and 5 add six constraints, and Step 7 adds the seventh.
A condition is written with models.Q, a Q object: a filter condition, in the same double-underscore lookup syntax as filter(), kept as a value. Q(capacity__gt=0) reads “capacity greater than 0”, and Q(status='active', cancelled_at__isnull=True) reads “active, with no cancellation time”: both parts must hold. The | operator means “or”: Q(a) | Q(b) holds when either does. One rule compares two fields of the same row: an event must end after it starts. models.F('starts_at'), an F expression, names another column of the same row, so Q(ends_at__gt=models.F('starts_at')) reads “the end is later than the start”, and the database compares the two values itself. That is all this chapter needs. Chapter 22 combines Q objects in queries, with &, |, and ~, and uses F in queries and audits.
Table 21.2 lists every rule this chapter adds and where it lives. The time zone is the exception: no SQL condition can know the list of real time-zone names, so it stays a validator.
| Rule | Mechanism | Model |
|---|---|---|
| One active registration per member and event | Conditional UniqueConstraint | Registration |
| cancelled_at filled exactly when cancelled | CheckConstraint | Registration |
| Never cancelled before it was made | CheckConstraint with F | Registration |
| Status is active or cancelled | CheckConstraint | Registration |
| One current organizer assignment | Conditional UniqueConstraint | OrganizerAssignment |
| Never revoked before it started | CheckConstraint with F | OrganizerAssignment |
| Capacity is more than 0 | CheckConstraint | Event |
| An event ends after it starts | CheckConstraint with F | Event |
| Status is draft, published, or cancelled | CheckConstraint | Event |
| Time zone is a real name | Field validator | Event |
| Email stored in lower case | CheckConstraint and the manager | User |
How the three places sit on the paths a row can take to its table is drawn in Figure 21.1.

One rule for some rows: a conditional unique constraint
Sai may cancel her place at the meetup and register again later. Her cancelled registration stays, because Chapter 2’s rules keep cancellations as history, so a plain unique rule on event and member would refuse her second registration. The conditional constraint builds an index that holds only active rows: cancelled rows are outside it, and a second active row for the same event and member collides with the first, as Figure 21.2 shows.

Under the Hood: what the constraints become in SQLite
A UniqueConstraint with a condition is not written as a table constraint. Django creates a partial index: CREATE UNIQUE INDEX "registration_one_active" ON "registrations_registration" ("event_id", "member_id") WHERE "status" = 'active'. The database keeps the index up to date on every write, and a write that would put a second entry for one pair into it fails. A CheckConstraint is part of the table’s definition. SQLite cannot add a CHECK to an existing table, so Django rebuilds the table: it creates new__registrations_registration with the rule, copies every row across, drops the old table, renames the new one, and recreates its indexes. Every row is copied, so one row that breaks the rule stops the whole migration, which is why Step 6 checks the data first. Two details from earlier chapters show up in the same SQL. PositiveIntegerField already writes CHECK ("capacity" >= 0), which allows zero; this chapter’s rule makes it > 0. And choices writes nothing at all: the database never knew the status list until now. On PostgreSQL, from Chapter 32, Django adds a constraint with ALTER TABLE instead of rebuilding.
IntegrityError and ValidationError
The same broken rule can reach you as two different errors, depending on how the row was written.
Prefer a constraint, a validator, or both?
If the database can express the rule, make it a constraint: nothing else covers update(), the shell, and every future script. Then give it a violation_error_message, so that full_clean(), and the forms that call it from Chapter 24, explain the rule in words a member understands, before the database has to refuse anything. If the database cannot express the rule, such as “this is a real time-zone name”, use a validator, and remember that it protects only code that validates. Django’s default message, Constraint “registration_one_active” is violated., is written for programmers; this chapter replaces it on every constraint.
IntegrityError comes from the database, during save(), create(), update(), or a migration. It means the write did not happen. ValidationError comes from Python, during full_clean(), before anything is written; its messages list the problems. A program should treat IntegrityError as the last line of defence, not as the normal way of telling a member that they are already registered.
Why a check in Python is not enough
Chapter 20 asked why a check in Python code alone cannot stop Sai’s second active registration. Imagine Otahque’s register view doing the obvious thing: look for an active registration for Sai and the meetup, and create one if there is none. Sai double-clicks. Two requests arrive a few milliseconds apart and are handled at the same time. Figure 21.3 follows them.

Each request checks before either one writes, so both checks pass, and both insert. No amount of checking in Python fixes this, because the gap between checking and writing is always there. The database closes it: it applies the unique index to each write as the write happens, one at a time, so the second insert fails whatever either request believed. The Custom Way in How We Build It plays this out with two calls. The harder version of the race, two members competing for the last place in a full event, involves counting rows rather than one pair, and needs a transaction and a lock; Chapter 33 builds it on PostgreSQL.
Email letter case: the decision
Chapter 17 left a product question for this chapter: are two addresses that differ only in capital letters one member? Mail systems treat the part after @ as case-insensitive. The part before it is case-sensitive in principle, but in practice almost every provider delivers Sai@example.org and sai@example.org to the same mailbox, and people type capitals by accident. If Otahque treated them as different, Sai could create a second account by mistake, and sign-in would fail when she typed her address differently.
Three options were considered: compare addresses without regard to case but store them as typed; store every address in lower case; or keep exact matching and accept duplicate accounts. Otahque’s decision, recorded in this chapter, is the second: every email address is stored in lower case. Three places carry it. The user manager lower-cases the whole address in create_user(), and in the lookup that sign-in uses. The model’s clean() lower-cases it during validation. And a CheckConstraint refuses any row whose email differs from its lower-case form, so a script that saves Sai@example.org directly is refused. Because the stored form is always lower case, Chapter 17’s unique=True on the email now treats Sai@Example.org and sai@example.org as the same address.
Two consequences come with the decision. The address a member sees on their account is lower-cased, even if they typed capitals. And SQLite’s LOWER() function changes only the letters A to Z, so on SQLite the constraint cannot catch an uppercase letter such as É that a script saves directly; Python’s lower() in the manager and clean() does handle it. PostgreSQL, from Chapter 32, lower-cases every letter. The L5 interview question returns to this.
In practice: importing events from a spreadsheet
Situation. Sam keeps last year’s events in a spreadsheet and wants them in Otahque. A script reads each row and creates an event with Event.objects.create(), or with bulk_create() for speed.
Application. Neither call validates, so a blank capacity cell read as 0, or a misspelt time zone, would be stored. With this chapter’s constraints, the capacity row is refused with an IntegrityError that names event_capacity_gt_0. A careful import script also calls full_clean() on each object first, so it can report every bad row with its line number before writing any.
Consideration. The time-zone rule is a validator, so only the script’s full_clean() call catches it. Chapter 41 builds Otahque’s import commands, and decides how a partly bad file is reported.
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 002How We Build It
Start from Chapter 20, in the folder containing manage.py, with your own .env, the locked environment, 36 passing tests, every migration applied, and the rows from Chapter 20: Sam, Sai, and Raj, three events, Sam’s organizer assignment, and three active registrations. Step 2 adds some deliberately bad rows. Step 3 writes the tests first. Steps 4 and 5 add the rules to events/models.py and registrations/models.py, and Step 6 finds and fixes the bad rows, then creates and applies two migrations. Step 7 changes accounts/managers.py and accounts/models.py for the email decision, with a third migration. Step 8 watches the database refuse bad rows, and Step 9 updates the ERD and commits. At the end, 51 tests pass and the public pages are unchanged.
The Custom Way
This illustration plays out Sai’s double-click with plain sqlite3, in memory; do not add it to the project. Instead of two real requests at the same time, it runs each request’s check before either insert, which is the order that matters:
import sqlite3
db = sqlite3.connect(':memory:')
db.execute('''
CREATE TABLE place (event INTEGER, member TEXT,
status TEXT)
''')
def has_place(event, member):
found = db.execute(
"SELECT 1 FROM place WHERE event = ? AND member = ?"
" AND status = 'active'", (event, member)
).fetchone()
return found is not None
def add_place(event, member):
db.execute("INSERT INTO place VALUES (?, ?, 'active')",
(event, member))
first_free = not has_place(1, 'Sai') # request A checks
second_free = not has_place(1, 'Sai') # request B checks
if first_free:
add_place(1, 'Sai') # request A inserts
if second_free:
add_place(1, 'Sai') # request B inserts
print(db.execute('SELECT COUNT(*) FROM place').fetchone())
db.execute('DELETE FROM place')
db.execute("CREATE UNIQUE INDEX one_active ON place"
" (event, member) WHERE status = 'active'")
add_place(1, 'Sai')
try:
add_place(1, 'Sai')
except sqlite3.IntegrityError as error:
print('refused:', error)
print(db.execute('SELECT COUNT(*) FROM place').fetchone())(2,)
refused: UNIQUE constraint failed: place.event, place.member
(1,)Both checks found no active place, so both inserts ran, and Sai holds two places. After CREATE UNIQUE INDEX ... WHERE, the hand-written partial index, the second insert is refused by the database itself, however the checks went. Now list what the hand-written version still lacks: the index lives outside any model, so nothing keeps it in step with the code; the error is a bare sqlite3 message for programmers; and nothing can check the rule before saving to show a member a sentence. UniqueConstraint gives you all three.
The Django Way
Nine steps follow. Step 1 checks the start, Step 2 creates bad rows on purpose, Step 3 writes the tests, Steps 4 and 5 write the rules, Step 6 fixes the data and migrates, Step 7 adds the email rule, Step 8 tries to break every rule, and Step 9 commits.
Step 1: Check the starting point
Run every test, beside manage.py, in PowerShell, Git Bash, a macOS shell, or Linux/WSL Bash:
uv run python manage.py testExpected result, shortened with ...:
Found 36 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
....................................
...
Ran 36 tests in ...
OK
Destroying test database for alias 'default'...Then start the shell, in any of the four shells, with uv run python manage.py shell, and count the rows:
15 objects imported automatically (use -v 2 for details).
Python 3.14.9 ...
Type "help", "copyright", "credits" or "license" for ...
(InteractiveConsole)
>>> Event.objects.count(), User.objects.count()
(3, 3)
>>> Registration.objects.filter(status='active').count()
3
>>> OrganizerAssignment.objects.count()
1
>>> exit()
now exiting InteractiveConsole...Three events, three members, three active registrations, and Sam’s assignment, as Chapter 20 left them. If your numbers differ, rows are left from experiments of your own. Keep them: Step 6 searches for rows that break the new rules, whatever rows you have, and shows how to fix each kind.
Step 2: See the gaps
Start the shell again. First, an event with two typing mistakes, checked with full_clean() and then saved:
>>> from datetime import UTC, datetime
>>> social = Event(
... title='Winter social',
... starts_at=datetime(2027, 1, 14, 18, 0, tzinfo=UTC),
... ends_at=datetime(2027, 1, 14, 21, 0, tzinfo=UTC),
... timezone='Europe/Londn',
... location='Leeds Central Library',
... capacity=0,
... )
>>> social.full_clean()
>>> social.save()
>>> Event.objects.filter(title='Winter social').count()
1full_clean() printed nothing, so it found nothing wrong: zero is a valid positive-integer value, and nothing checks a time-zone name. The draft event is stored, with both mistakes. Now Sai’s double-click, and a cancellation without a time:
>>> meetup = Event.objects.get(title='Python meetup')
>>> sai = User.objects.get(email='sai@example.org')
>>> Registration.objects.create(event=meetup, member=sai)
<Registration: sai@example.org at Python meetup>
>>> active = meetup.registrations.filter(status='active')
>>> active.filter(member=sai).count()
2
>>> raj_place = meetup.registrations.get(
... member__email='raj@example.org'
... )
>>> raj_place.status = Registration.Status.CANCELLED
>>> raj_place.save()
>>> print(raj_place.cancelled_at)
NoneSai now holds two active places, and Raj’s registration says cancelled, but not when. Last, Sai signs up again with capital letters:
>>> User.objects.create_user(
... 'Sai@Example.ORG', display_name='Sai'
... )
<User: Sai@example.org>
>>> User.objects.count()
4Chapter 17’s manager lower-cased only the domain, so Sai@example.org differs from sai@example.org, and unique=True accepts it as a new member. Leave the shell with exit(). Keep all four bad rows: Step 6 and Step 7 find them again, the way you would find real ones.
Step 3: Write the tests first
The tests describe each rule before it exists. Start with events/tests.py. At the top, add one import line, from django.db import IntegrityError, transaction, after the ValidationError import, so that the block begins:
from datetime import UTC, datetime, timedelta
from pathlib import Path
from django.contrib.auth import get_user_model
from django.contrib.staticfiles import finders
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import ProtectedErrorNext, find the class EventModelTests, from Chapter 16, and change its base class from SimpleTestCase to TestCase:
class EventModelTests(TestCase):
"""The Event model's rules, checked with the database."""
Chapter 16 used SimpleTestCase because full_clean() then needed no database. From this chapter, full_clean() also checks the model’s constraints, and that asks the database, which SimpleTestCase forbids.
Common Error: database queries are not allowed in SimpleTestCase
If you skip that change, test_status_starts_draft_and_is_checked fails after Step 4 with DatabaseOperationForbidden: Database queries to 'default' are not allowed in SimpleTestCase subclasses. The traceback passes through validate_constraints(). Change the class to TestCase, which gives each test a database inside a transaction.
Then add a class at the end of the file, after OrganizerAssignmentTests:
class EventRuleTests(TestCase):
"""Database constraints refuse impossible events."""
def test_capacity_must_be_more_than_zero(self):
with self.assertRaises(IntegrityError):
with transaction.atomic():
save_event(capacity=0)
self.assertFalse(Event.objects.exists())
def test_end_must_be_after_start(self):
start = datetime(2027, 2, 1, 18, tzinfo=UTC)
with self.assertRaises(IntegrityError):
with transaction.atomic():
save_event(starts_at=start, ends_at=start)
self.assertFalse(Event.objects.exists())
def test_only_listed_statuses_can_be_saved(self):
for status in Event.Status.values:
save_event(status=status)
with self.assertRaises(IntegrityError):
with transaction.atomic():
save_event(status='archived')
self.assertEqual(Event.objects.count(), 3)
def test_unknown_time_zone_fails_validation(self):
event = save_event(timezone='Europe/Londn')
with self.assertRaises(ValidationError) as caught:
event.full_clean()
self.assertEqual(
caught.exception.message_dict,
{'timezone': [
'Europe/Londn is not a known time zone.'
]},
)
def test_one_current_assignment_per_event(self):
event = save_event()
sam = User.objects.create_user(
'sam@example.org', display_name='Sam'
)
first = OrganizerAssignment.objects.create(
event=event, member=sam
)
with self.assertRaises(IntegrityError):
with transaction.atomic():
OrganizerAssignment.objects.create(
event=event, member=sam
)
day = timedelta(days=1)
first.revoked_at = first.assigned_at + day
first.save()
OrganizerAssignment.objects.create(
event=event, member=sam
)
self.assertEqual(
event.organizer_assignments.count(), 2
)
def test_revoked_never_before_assigned(self):
event = save_event()
sam = User.objects.create_user(
'sam@example.org', display_name='Sam'
)
early = OrganizerAssignment.objects.create(
event=event, member=sam
)
day = timedelta(days=1)
early.revoked_at = early.assigned_at - day
with self.assertRaises(IntegrityError):
with transaction.atomic():
early.save()Each refused write sits inside transaction.atomic(). A TestCase runs every test inside a transaction, and after a database error, that transaction cannot run another query. The inner atomic() block marks a point to roll back to, so the test can go on to check that nothing was saved. The status test saves one event for every value in Event.Status.values, then tries one value that is not in the list: if someone later adds a status to the model but not to the constraint, the loop fails and says so. The time-zone test saves first, which works, because only validation checks time zones, and then calls full_clean(). The assignment test revokes the first assignment and makes a new one, proving that the rule is “one current assignment”, not “one ever”.
Now registrations/tests.py. Its imports gain three lines, and timedelta joins the datetime import; cancellations in these tests take the current time, which always comes after the registration’s. The top of the file becomes:
from datetime import UTC, datetime, timedelta
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import ProtectedError
from django.test import TestCase
from django.utils import timezone
from events.models import Event
from .models import Registration
User = get_user_model()Add five methods at the end of the file, indented inside RegistrationTests, so that they share its event, member, and active registration:
def test_second_active_registration_is_refused(self):
with self.assertRaises(IntegrityError):
with transaction.atomic():
Registration.objects.create(
event=self.event, member=self.member
)
self.assertEqual(
self.event.registrations.count(), 1
)
def test_member_can_register_after_cancelling(self):
self.registration.status = 'cancelled'
self.registration.cancelled_at = timezone.now()
self.registration.save()
Registration.objects.create(
event=self.event, member=self.member
)
active = self.event.registrations.filter(
status=Registration.Status.ACTIVE
)
self.assertEqual(active.count(), 1)
def test_cancelled_at_matches_status(self):
rows = Registration.objects.filter(
pk=self.registration.pk
)
for status, cancelled_at in [
('cancelled', None),
('active', timezone.now()),
]:
with self.subTest(status=status):
with self.assertRaises(IntegrityError):
with transaction.atomic():
rows.update(
status=status,
cancelled_at=cancelled_at,
)
def test_cancelled_never_before_registered(self):
rows = Registration.objects.filter(
pk=self.registration.pk
)
day = timedelta(days=1)
before = self.registration.registered_at - day
with self.assertRaises(IntegrityError):
with transaction.atomic():
rows.update(status='cancelled',
cancelled_at=before)
def test_full_clean_explains_a_duplicate(self):
duplicate = Registration(
event=self.event, member=self.member
)
with self.assertRaises(ValidationError) as caught:
duplicate.full_clean()
self.assertEqual(
caught.exception.messages,
['This member already has a place at '
'this event.'],
)The cancellation test uses update() on purpose: it writes without calling save(), which is exactly the path that only a constraint can guard. subTest() runs the same check for both wrong combinations and reports each separately. The order test dates a cancellation one day before the registration, the kind of row a careless import could write. The last test is the friendly side: full_clean() on a duplicate raises ValidationError with the message you will write in Step 5, before anything reaches the database.
Last, accounts/tests.py. One line of Chapter 18’s test_create_user_saves_a_member pinned the old behaviour, which kept capitals before the @. Change its expected email to lower case:
self.assertEqual(saved.email, 'sai@example.org')That is how a test records a decision: when the decision changes, the test changes with it, in the same commit. Then add four methods at the end of the file, inside UserCreationTests:
def test_email_differing_in_case_is_refused(self):
User.objects.create_user(
'sai@example.org', display_name='Sai'
)
with self.assertRaises(IntegrityError):
User.objects.create_user(
'SAI@example.org', display_name='Sai'
)
def test_upper_case_email_cannot_be_saved(self):
user = User(
email='Sai@example.org', display_name='Sai'
)
with self.assertRaises(IntegrityError):
user.save()
def test_full_clean_lower_cases_the_email(self):
user = User(
email='Sai@Example.ORG', display_name='Sai'
)
user.set_unusable_password()
user.full_clean()
self.assertEqual(user.email, 'sai@example.org')
def test_sign_in_lookup_ignores_case(self):
sai = User.objects.create_user(
'sai@example.org', display_name='Sai'
)
found = User.objects.get_by_natural_key(
'SAI@Example.org'
)
self.assertEqual(found, sai)get_by_natural_key() is the method Django’s sign-in uses to find a member by the address they type; Chapter 27 builds sign-in on it. set_unusable_password() gives the unsaved user a password value, so that full_clean() checks only what this test is about. Run every test:
uv run python manage.py testExpected result, shortened with ...:
Found 51 test(s).
...
ERROR: test_sign_in_lookup_ignores_case (accounts.test...
...
accounts.models.User.DoesNotExist: User matching query...
...
FAIL: test_create_user_saves_a_member (accounts.tes...
...
AssertionError: 'Sai@example.org' != 'sai@example.org'
...
FAIL: test_capacity_must_be_more_than_zero (events.tes...
...
AssertionError: IntegrityError not raised
...
FAILED (failures=15, errors=1)
Destroying test database for alias 'default'...Fifteen tests are new, and every new rule fails, each for the reason it should: an expected IntegrityError or ValidationError is not raised, an email keeps its capitals, and the case-insensitive lookup finds nobody. The failures count each subTest separately, so the cancellation test counts twice. One new test already passes: test_member_can_register_after_cancelling, because nothing refuses a second registration yet. It is there to make sure the rule you add stays conditional.
Step 4: Add the event rules
Open events/models.py. Replace its three import lines with these imports and a validator function, so the file begins:
"""Models for Otahque's events."""
from zoneinfo import available_timezones
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
def validate_timezone_name(value):
"""Refuse names missing from the time-zone database."""
if value not in available_timezones():
raise ValidationError(
'%(value)s is not a known time zone.',
code='unknown_timezone',
params={'value': value},
)A validator is a function that takes a value and raises ValidationError if the value is wrong. zoneinfo is the Python standard library’s time-zone module, which Chapter 16’s time-zone field already relied on, and available_timezones() returns the set of names it knows, read on Windows from the tzdata package in the project’s lock file. The message uses %(value)s with params, rather than an f-string, so that Django can later translate the sentence; code names the kind of error for code that checks it.
In the Event class, attach the validator to the time-zone field, which becomes:
timezone = models.CharField(
max_length=64, validators=[validate_timezone_name]
)Then replace Event’s Meta class, which held only the ordering, with this:
class Meta:
ordering = ['starts_at']
constraints = [
models.CheckConstraint(
condition=models.Q(capacity__gt=0),
name='event_capacity_gt_0',
violation_error_message=(
'Capacity must be more than 0.'
),
),
models.CheckConstraint(
condition=models.Q(
ends_at__gt=models.F('starts_at')
),
name='event_ends_after_start',
violation_error_message=(
'An event must end after it starts.'
),
),
models.CheckConstraint(
condition=models.Q(status__in=[
'draft', 'published', 'cancelled',
]),
name='event_status_valid',
violation_error_message=(
'Status must be draft, published, '
'or cancelled.'
),
),
]Each name starts with the model it protects, so an error message points straight at the rule. The status list is written out, rather than taken from Status, for a reason the next Common Error shows; the migration stores these literal values anyway, and the status test from Step 3 fails if the two lists ever disagree.
Common Error: Status inside Meta
Writing condition=models.Q(status__in=Status.values) stops the project with NameError: name 'Status' is not defined. A nested class such as Meta cannot see the names defined beside it in the model’s class body. Write the values out, as in the listing. In the same spirit, CheckConstraint(check=...) from older articles fails with TypeError: CheckConstraint.__init__() got an unexpected keyword argument 'check': Django 6.0 removed that spelling, and the argument is now condition.
Finally, replace OrganizerAssignment’s Meta class at the end of the file:
class Meta:
ordering = ['assigned_at']
constraints = [
models.UniqueConstraint(
fields=['event', 'member'],
condition=models.Q(revoked_at__isnull=True),
name='assignment_one_current',
violation_error_message=(
'This member already organizes this '
'event.'
),
),
models.CheckConstraint(
condition=(
models.Q(revoked_at__isnull=True)
| models.Q(revoked_at__gte=models.F(
'assigned_at'
))
),
name='assignment_revoked_after_assigned',
violation_error_message=(
'An assignment cannot be revoked before '
'it starts.'
),
),
]The condition revoked_at__isnull=True selects current assignments only, so a revoked assignment stays as history and does not block a new one. The second rule compares two columns of the same row with F, as the event’s end-time rule does: a revocation is at or after the assignment it ends. Its first branch says that a current assignment, with no revocation time, is fine, which is the database’s own behaviour for an empty value in a CHECK; written out, the rule says what it means. Check the project:
uv run python manage.py checkSystem check identified no issues (0 silenced).Step 5: Add the registration rules
Open registrations/models.py and replace the Meta class of Registration with this:
class Meta:
ordering = ['registered_at']
constraints = [
models.UniqueConstraint(
fields=['event', 'member'],
condition=models.Q(status='active'),
name='registration_one_active',
violation_error_message=(
'This member already has a place at '
'this event.'
),
),
models.CheckConstraint(
condition=models.Q(status__in=[
'active', 'cancelled',
]),
name='registration_status_valid',
violation_error_message=(
'Status must be active or cancelled.'
),
),
models.CheckConstraint(
condition=(
models.Q(status='active',
cancelled_at__isnull=True)
| models.Q(status='cancelled',
cancelled_at__isnull=False)
),
name='cancelled_at_matches_status',
violation_error_message=(
'A cancelled registration needs a '
'cancellation time; an active one has '
'none.'
),
),
models.CheckConstraint(
condition=(
models.Q(cancelled_at__isnull=True)
| models.Q(cancelled_at__gte=models.F(
'registered_at'
))
),
name='cancelled_after_registered',
violation_error_message=(
'A registration cannot be cancelled '
'before it was made.'
),
),
]The first rule is the one Chapter 20 promised: unique event and member, among active rows. The third reads “active with no cancellation time, or cancelled with one”, the only two combinations that make sense. The fourth keeps time in order: a cancellation is never earlier than the registration it ends. Check the project again:
uv run python manage.py checkSystem check identified no issues (0 silenced).Step 6: Fix the rows that break the rules, then migrate
A constraint applies to every row already in the table, so the migration fails if one row breaks it. Find those rows first. Start the shell and ask one question per rule:
>>> from zoneinfo import available_timezones
>>> Event.objects.filter(capacity__lte=0)
<QuerySet [<Event: Winter social>]>
>>> Event.objects.filter(
... ends_at__lte=models.F('starts_at')
... )
<QuerySet []>
>>> Registration.objects.filter(
... cancelled_at__lt=models.F('registered_at')
... )
<QuerySet []>
>>> OrganizerAssignment.objects.filter(
... revoked_at__lt=models.F('assigned_at')
... )
<QuerySet []>
>>> Event.objects.exclude(status__in=Event.Status.values)
<QuerySet []>
>>> [event.title for event in Event.objects.all()
... if event.timezone not in available_timezones()]
['Winter social']
>>> Registration.objects.filter(
... status='cancelled', cancelled_at__isnull=True
... )
<QuerySet [<Registration: raj@example.org at Python mee...
>>> Registration.objects.filter(
... status='active', cancelled_at__isnull=False
... )
<QuerySet []>The registration line is shortened here; it ends Python meetup>]>. exclude() returns the rows that do not match its condition, which is how you find rows outside a list. A list comprehension handles the time zones, because the database cannot check names against Python’s list.
Duplicates take one more idea. values_list() returns each row’s chosen fields as a tuple, and Counter, from the standard library’s collections module, counts how often each tuple appears; most_common(1) gives the most frequent:
>>> from collections import Counter
>>> active = Registration.objects.filter(status='active')
>>> pairs = active.values_list(
... 'event__title', 'member__email'
... )
>>> Counter(pairs).most_common(1)
[(('Python meetup', 'sai@example.org'), 2)]
>>> current = OrganizerAssignment.objects.filter(
... revoked_at__isnull=True
... )
>>> ids = current.values_list('event', 'member')
>>> Counter(ids).most_common(1)
[((1, 1), 1)]Sai’s pair appears twice among active registrations, which breaks the new rule. The most common assignment pair appears once, so there are no duplicate assignments; your ids may differ. Fix each problem with the smallest change that makes the row true, never by deleting the database:
>>> social = Event.objects.get(title='Winter social')
>>> social.capacity = 30
>>> social.timezone = 'Europe/London'
>>> social.full_clean()
>>> social.save()
>>> raj_place = Registration.objects.get(
... status='cancelled', cancelled_at__isnull=True
... )
>>> raj_place.cancelled_at = timezone.now()
>>> raj_place.save()
>>> extra = active.filter(
... member__email='sai@example.org',
... event__title='Python meetup',
... ).last()
>>> extra.delete()
(1, {'registrations.Registration': 1})
>>> Counter(pairs.all()).most_common(1)
[(('Python meetup', 'sai@example.org'), 1)]The winter social keeps its row, with a real capacity and time zone; this time full_clean() checks the constraints too, against the database, and passes. Raj’s cancellation gets its time: timezone here is Django’s django.utils.timezone, which the shell imports for you, and now() is the current time in UTC. Sai’s second registration was never a real place, only a double-click, so it is deleted; last() picks the newer of the two, because registrations are ordered by registered_at. pairs keeps the rows it fetched the first time, Chapter 19’s result cache, so pairs.all() asks the database again, and now the pair appears once. Leave the shell with exit().
Now create the migrations, for both apps at once. --name gives each new file a readable name, instead of one made from the constraint names. In any of the four shells:
uv run python manage.py makemigrations --name rulesMigrations for 'events':
events\migrations\0003_rules.py
~ Alter field timezone on event
+ Create constraint event_capacity_gt_0 on model event
+ Create constraint event_ends_after_start on model e...
+ Create constraint event_status_valid on model event
+ Create constraint assignment_one_current on model ...
+ Create constraint assignment_revoked_after_assigned...
Migrations for 'registrations':
registrations\migrations\0002_rules.py
+ Create constraint registration_one_active on model ...
+ Create constraint registration_status_valid on mod...
+ Create constraint cancelled_at_matches_status on m...
+ Create constraint cancelled_after_registered on mod...On macOS and Linux, the paths use /. The time-zone field is altered because its validators changed; a validator lives in Python, so that operation runs no SQL. Read the SQL for the registrations migration:
uv run python manage.py sqlmigrate registrations 0002Expected result, with long lines shortened:
BEGIN;
--
-- Create constraint registration_one_active on model re...
--
CREATE UNIQUE INDEX "registration_one_active" ON "regist...
--
-- Create constraint registration_status_valid on model ...
--
CREATE TABLE "new__registrations_registration" ("id" int...
INSERT INTO "new__registrations_registration" ("id", "st...
DROP TABLE "registrations_registration";
ALTER TABLE "new__registrations_registration" RENAME TO ...
...
COMMIT;On your screen, the first CREATE UNIQUE INDEX line ends WHERE "status" = 'active';, the partial index from the Under the Hood box. Each CheckConstraint rebuilds the table: create new__registrations_registration with the rule, copy the rows, drop the old table, rename the new one, and recreate its indexes. Apply both migrations:
uv run python manage.py migrateOperations to perform:
Apply all migrations: accounts, admin, auth, ...
Running migrations:
Applying events.0003_rules... OK
Applying registrations.0002_rules... OKCommon Error: a migration stopped by an existing row
If a row still breaks a rule, migrate stops with a long traceback ending, for example, django.db.utils.IntegrityError: CHECK constraint failed: event_capacity_gt_0. Each migration runs in a transaction, so the failed one is not applied: showmigrations still shows [ ] beside it, and your rows are as they were. Run the matching question from this step’s first session, fix the row it finds, and run migrate again. Do not delete the migration or the database.
Run every test:
uv run python manage.py testExpected result, shortened with ...:
Found 51 test(s).
...
FAILED (failures=4, errors=1)
Destroying test database for alias 'default'...Every event and registration rule now passes. The five remaining problems are all in accounts: the email decision is the next step.
Step 7: Store email addresses in lower case
Open accounts/managers.py and add two methods to UserManager, after the line use_in_migrations = True:
@classmethod
def normalize_email(cls, email):
"""Store the whole address in lower case."""
return super().normalize_email(email).lower()
def get_by_natural_key(self, email):
"""Find the member with this email, in any case."""
return super().get_by_natural_key(
self.normalize_email(email)
)normalize_email() is the method Chapter 17’s create_user() already calls. Django’s version, which super() runs first, lower-cases only the domain; this one then lower-cases the whole address. It is a class method, as in Django, so it can be called on the class itself. get_by_natural_key() is the lookup that sign-in uses to find a member from the address they typed, so it normalizes the typed address in the same way before searching.
Then open accounts/models.py. Add one import, so the imports read:
from django.contrib.auth.models import (
AbstractBaseUser,
PermissionsMixin,
)
from django.db import models
from django.db.models.functions import Lower
from django.utils import timezone
from .managers import UserManagerLower is a database function: Django turns Lower('email') into SQL LOWER("email"). At the end of the User class, replace the __str__() method with a Meta class, the same __str__(), and a clean() method:
class Meta:
constraints = [
models.CheckConstraint(
condition=models.Q(email=Lower('email')),
name='user_email_lowercase',
violation_error_message=(
'Email addresses are stored in lower '
'case.'
),
),
]
def __str__(self):
return self.email
def clean(self):
"""Store the email in lower case before validating."""
super().clean()
self.email = UserManager.normalize_email(self.email)The condition compares each row’s email with its own lower-case form, so it holds only for addresses with no capitals. clean() first runs the parent class’s clean(), which tidies the Unicode characters of the sign-in field, then lower-cases the email, so that full_clean() fixes the address instead of refusing it. Find the members that would break the new rule:
>>> User.objects.exclude(email=functions.Lower('email'))
<QuerySet [<User: Sai@example.org>]>
>>> twin = User.objects.get(email='Sai@example.org')
>>> links = twin.registrations, twin.organizer_assignments
>>> [manager.count() for manager in links]
[0, 0]
>>> twin.delete()
(1, {'accounts.User': 1})
>>> User.objects.count()
3functions is django.db.models.functions, imported by the shell, so functions.Lower is the same Lower as in the model. The account is Step 2’s accidental second Sai. Before deleting a member, check that nothing points at them: this one has no registrations and no assignments, and the original sai@example.org keeps all of Sai’s places. If a real account had capitals, you would change its address with twin.email = twin.email.lower() and twin.save() instead. Leave the shell, then create and apply the migration:
uv run python manage.py makemigrations --name email_lowercase
uv run python manage.py migrateMigrations for 'accounts':
accounts\migrations\0002_email_lowercase.py
+ Create constraint user_email_lowercase on model user
Operations to perform:
Apply all migrations: accounts, admin, auth, ...
Running migrations:
Applying accounts.0002_email_lowercase... OKRun every test:
uv run python manage.py testExpected result, shortened with ...:
Found 51 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...................................................
...
Ran 51 tests in ...
OK
Destroying test database for alias 'default'...Thirty-six tests from before, and fifteen for the new rules, all passing.
Step 8: Try to break every rule
Start the shell. Each line below tries to write a bad row, using a different path:
>>> from django.core.exceptions import ValidationError
>>> meetup = Event.objects.get(title='Python meetup')
>>> sai = User.objects.get(email='sai@example.org')
>>> Registration.objects.create(event=meetup, member=sai)
Traceback (most recent call last):
...
django.db.utils.IntegrityError: UNIQUE constraint failed: ...
>>> second = Registration(event=meetup, member=sai)
>>> try:
... second.full_clean()
... except ValidationError as error:
... print(error.messages)
...
['This member already has a place at this event.']create() reached the database, which refused the row: the traceback’s last line continues registrations_registration.event_id, registrations_registration.member_id, the two columns of the partial index. full_clean() asked first, and explains the same rule in a sentence. Now an update(), which skips save() entirely, and a member signing up again in capitals:
>>> spring = Event.objects.filter(title='Spring planning')
>>> spring.update(capacity=0)
Traceback (most recent call last):
...
django.db.utils.IntegrityError: CHECK constraint failed: ...
>>> User.objects.create_user(
... 'SAI@Example.org', display_name='Sai'
... )
Traceback (most recent call last):
...
django.db.utils.IntegrityError: UNIQUE constraint failed: ...
>>> User.objects.get_by_natural_key('SAI@Example.org')
<User: sai@example.org>The capacity error ends event_capacity_gt_0, the constraint’s name. The sign-up error ends accounts_user.email: the manager lower-cased the address, so Chapter 17’s unique email refused it as a duplicate of Sai’s account, and the sign-in lookup finds her account however she types it. Last, the one rule that is only validation:
>>> social = Event.objects.get(title='Winter social')
>>> social.timezone = 'Europe/Londn'
>>> try:
... social.full_clean()
... except ValidationError as error:
... print(error.messages)
...
['Europe/Londn is not a known time zone.']
>>> social.refresh_from_db()
>>> social.timezone
'Europe/London'full_clean() refuses the name. save() would not have: the time-zone rule protects only code that validates, as Table 21.1 said. refresh_from_db() reloads the stored row, undoing the change in memory. Every refused write left the data as it was. Leave the shell with exit().
Step 9: Update the ERD and commit
Chapter 15’s ERD, in docs/design/erd.md, still lists two rules as future work. Open it. In the section “Rules the structure holds”, add three items after the capacity item:
- PR-2: cancelled_at is filled exactly when status is
cancelled (CHECK constraint).
- A cancellation is never earlier than its registration,
and a revocation never earlier than its assignment
(CHECK constraints).
- Email addresses are stored in lower case, so two
that differ only in letter case are one member
(CHECK constraint; decided in Chapter 21).Then delete two items that this chapter answered: in “Rules that need more than structure”, the item beginning PR-2, cancelled_at filled exactly, and in “Open questions”, the item beginning Are addresses that differ only in letter case. Each is two lines long. Look at what changed:
git status --short M accounts/managers.py
M accounts/models.py
M accounts/tests.py
M docs/design/erd.md
M events/models.py
M events/tests.py
M registrations/models.py
M registrations/tests.py
?? accounts/migrations/0002_email_lowercase.py
?? events/migrations/0003_rules.py
?? registrations/migrations/0002_rules.pyEight changed files and three new migrations. Your fixed rows are not listed: they live in db.sqlite3, which Git ignores. Commit:
git add accounts docs events registrations
git commit -m "Add constraints and lower-case emails"When something goes wrong
| Symptom | Likely cause | Safe recovery |
|---|---|---|
| Found 51 test(s), FAILED (failures=15, errors=1) | The rules do not exist yet | Expected in Step 3; continue with Step 4 |
| NameError: name 'Status' is not defined | Status used inside Meta | Write the values out as a list |
| unexpected keyword argument 'check' | An older spelling | Use condition= |
| DatabaseOperationForbidden in a model test | full_clean() now queries the database | Change the class to TestCase |
| Missing migrations in the tests | Models changed, no migration yet | Run Step 6's makemigrations |
| IntegrityError during migrate | A row breaks the new rule | Find it with Step 6's questions, fix it, migrate again |
| TransactionManagementError in a test | A query after an IntegrityError | Wrap the refused write in transaction.atomic() |
| IntegrityError on create() or update() | The rule refused a bad row | Intended; nothing was written |
| Constraint “...” is violated. | No violation_error_message | Add a message for people |
| A time-zone typo saved without error | save() does not validate | Call full_clean() before saving |
The TransactionManagementError row deserves a word. Inside a TestCase, a database error spoils the test’s transaction, and the next query fails with An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. That is why every expected IntegrityError in Step 3 sits inside its own transaction.atomic().
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 003Verify Your Work
Work through Table 21.4 from the folder that holds manage.py. The test rows come first: they hold every rule in place, whatever rows your database holds.
| Check | Command or action | Expected result |
|---|---|---|
| Red stage seen | The Step 3 run, before the rules | Found 51 test(s); FAILED (failures=15, errors=1) |
| Tests pass | uv run python manage.py test | Found 51 test(s); OK |
| Migrations applied | uv run python manage.py showmigrations accounts events registrations | [X] beside 0002_email_lowercase, 0003_rules, and 0002_rules |
| Partial index in the SQL | sqlmigrate registrations 0002 | CREATE UNIQUE INDEX ... WHERE "status" = 'active' |
| Duplicate refused | Step 8's create() for Sai | IntegrityError; full_clean() shows the message |
| update() refused | Step 8's update(capacity=0) | IntegrityError naming event_capacity_gt_0 |
| Emails lower case | Step 7's first shell question, run again | <QuerySet []> |
| ERD updated | docs/design/erd.md | PR-2 and the email rule under Rules the structure holds |
| Committed | git status --short | No output |
| Not verified | macOS, Linux, WSL; PostgreSQL | Readers on those systems; Chapter 32 |
The commands were checked in Windows PowerShell 5.1 and Git Bash, with the shell sessions typed into a Windows console. PostgreSQL adds constraints without rebuilding tables and lower-cases every letter; Chapter 32 runs these tests there.
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 004Checkpoint: Quiz and Challenge
Quiz
Que. 2 Chapter 19 saved an event with capacity=0, and full_clean() in Step 2 accepted another. Name the two reasons, and say which one this chapter fixed for every path.
Flip to check your answerFold answer back
Answer. save() does not call full_clean(), and even full_clean() had no rule against zero, because PositiveIntegerField allows it. The event_capacity_gt_0 constraint fixes both: the database refuses zero on every write, and full_clean() reports it with the constraint’s message.
Que. 3 Why is “one active registration per member and event” a conditional UniqueConstraint rather than unique_together on event and member?
Flip to check your answerFold answer back
Answer. A plain unique rule would refuse Sai’s new registration after she cancelled, because her cancelled row keeps the same event and member. The condition status='active' puts only active rows in the index, so history stays and re-registering works.
Que. 4 Step 6’s first migrate would have failed with your bad rows still present. What makes that failure safe, and what is the right recovery?
Flip to check your answerFold answer back
Answer. Each migration runs in a transaction, so a failed one is not applied and no rows change; showmigrations shows [ ]. The recovery is to find the offending rows with a query per rule, fix or remove only those rows, and run migrate again, never to delete the migration or the database.
Que. 5 The time-zone rule is a validator, not a constraint. What does that mean for a script that calls save()?
Flip to check your answerFold answer back
Answer. The script can store a misspelt time zone, because only full_clean() runs validators. A script that writes events must call full_clean() first, as Chapter 41’s import commands will.
Que. 6 After this chapter, what happens when Sai signs up as SAI@Example.org?
Flip to check your answerFold answer back
Answer. The manager lower-cases the whole address to sai@example.org, and the existing unique email refuses it as a duplicate of her account. If code saved SAI@Example.org directly, without the manager, the user_email_lowercase constraint would refuse it.
Mini-Challenge
Que. 7 Raj cancelled his meetup place in Step 6, and asks whether he can register again. Predict the answer, then check it in the shell without keeping any change: register him again, try once more, and print what happens each time. Use transaction.atomic() and transaction.set_rollback(True), so that the database undoes everything at the end of the block.
Flip to check your answerFold answer back
Answer. He can register again, because his cancelled row is outside the partial index; a second active registration is refused. Here is one session that shows it:
>>> from django.db import IntegrityError, transaction
>>> raj = User.objects.get(email='raj@example.org')
>>> meetup = Event.objects.get(title='Python meetup')
>>> with transaction.atomic():
... again = Registration.objects.create(
... event=meetup, member=raj
... )
... print(again.status)
... try:
... with transaction.atomic():
... Registration.objects.create(
... event=meetup, member=raj
... )
... except IntegrityError as error:
... print('refused:', type(error).__name__)
... transaction.set_rollback(True)
...
active
refused: IntegrityError
>>> raj.registrations.count()
1The outer block holds the experiment; set_rollback(True) tells Django to roll it back instead of committing, so Raj still has only his cancelled registration afterwards. The inner block is the same pattern as the tests: it lets the refused insert fail without spoiling the outer transaction. An answer that keeps Raj’s new registration is also correct, if you meant him to register; it is your local data.
What We Learned
save(),update(), andbulk_create()do not validate;full_clean()runs field checks,clean(), uniqueness, and constraints, in that order, and only when called.- A rule the database can express belongs in a constraint, which refuses bad rows on every write path with
IntegrityError. CheckConstraint(condition=Q(...))writes aCHECK;UniqueConstraint(fields=..., condition=Q(...))writes a partial unique index that applies only to matching rows.violation_error_messageletsfull_clean()explain a constraint in words a member understands, before the database has to refuse.- A constraint migration checks every existing row; find and fix offending rows first, with one query per rule.
- A check in Python cannot stop two simultaneous requests; a unique index can, because the database applies it to each write as it happens.
- Otahque stores every email address in lower case: the manager,
clean(), and a constraint carry the decision.
Key terms
Use Table 21.5 to explain this chapter’s ideas in your own words.
| Term | Meaning |
|---|---|
| Validation | Python checks that raise ValidationError, run by full_clean(). |
| Validator | A function that checks one field value. |
| full_clean() | Runs field checks, clean(), uniqueness, and constraints. |
| Database constraint | A rule in the table's definition, applied to every write. |
| CheckConstraint | A rule that every row must satisfy. |
| Conditional UniqueConstraint | Uniqueness among rows that match a condition. |
| Partial index | An index holding only rows that match a WHERE clause. |
| Q object | A lookup condition kept as a value, combined with or (|) and and (&). |
| IntegrityError | The database refused a write. |
| violation_error_message | The text full_clean() shows for a broken constraint. |
| Race condition | A result that depends on the timing of simultaneous work. |
Readiness checkpoint: you are ready for Chapter 22 when all 51 tests pass, showmigrations shows the three new migrations applied, Step 8’s writes are refused in the shell, no member’s email has capitals, and git status --short prints nothing. Chapter 22 combines Q objects in queries and introduces F, which can compare two fields, such as a cancellation time and a registration time. Return to the relevant step if any result is missing.
Git Commit
Your Chapter 21 work was committed in Step 9. For the record, these were the commands, in any of the four shells, beside manage.py:
git add accounts docs events registrations
git status --shortM accounts/managers.py
A accounts/migrations/0002_email_lowercase.py
M accounts/models.py
M accounts/tests.py
M docs/design/erd.md
A events/migrations/0003_rules.py
M events/models.py
M events/tests.py
A registrations/migrations/0002_rules.py
M registrations/models.py
M registrations/tests.pygit commit -m "Add constraints and lower-case emails"The commit holds the rules and the migrations that create them. Your fixed rows are not in it: anyone who runs these migrations on their own database meets their own rows, which is why Step 6’s questions matter beyond this chapter.
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 005Test Your Knowledge: Interview Questions
These five questions rehearse the chapter at interview level, one at each of five levels from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead to a larger application with a team: attempt them now, and return to them after Chapters 32 and 64. They are extension questions, not a gate to the next chapter. Each code proof is a short file in the practice folder that starts by importing Chapter 16’s setup_django.py; run it from the folder that holds manage.py with uv run python ../practice/ followed by the file name. The proofs read your rows and roll back anything they try, so your data stays as it is.
L1 (Junior): What is the difference between validation and a database constraint in Django?
What the interviewer is testing: Do you know where each kind of rule runs, and which one actually guarantees the data?
Flip to check your answerFold answer back
Perfect answer: Validation is Python code that checks an object and raises ValidationError with messages: field validators, choices and max_length, the model’s clean(), and, since Django 4.1, the model’s constraints, all run by full_clean(). It runs only when something calls it: forms and the admin do, but save(), update(), and bulk_create() do not. A database constraint, such as a CheckConstraint or UniqueConstraint in Meta.constraints, is part of the table, so the database refuses every write that breaks it, from any code, and Django raises IntegrityError. I use a constraint for every rule the database can express, because it is the only guarantee, and validation, including a violation_error_message on each constraint, to explain problems to people before saving. Rules the database cannot express, such as “a real time-zone name”, stay validators, and I remember that they protect only callers that validate.
| Aspect | Validation | Database constraint |
|---|---|---|
| Runs | When full_clean() is called | On every INSERT and UPDATE |
| Error | ValidationError, with messages | IntegrityError |
| Covers update() | No | Yes |
Behind the scenes:
full_clean() -> fields, clean(), unique, constraints
save() -> no validation; database rules apply
update() -> no save(), no validation; rules apply
constraint -> refused write: IntegrityErrorCode proof: the same broken rule, asked of both:
import setup_django
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from events.models import Event
event = Event.objects.get(title='Spring planning')
event.capacity = 0
try:
event.full_clean()
except ValidationError as error:
print('validation:', error.messages)
try:
with transaction.atomic():
Event.objects.filter(pk=event.pk).update(capacity=0)
except IntegrityError as error:
print('database:', error)validation: ['Capacity must be more than 0.']
database: CHECK constraint failed: event_capacity_gt_0full_clean() explains the rule with the constraint’s message, before writing. update() skips validation, and the database refuses the write; the atomic() block keeps the failed statement from affecting anything else.
Common mistakes:
- Believing that
save()validates, or thatchoicesrestricts what the database stores. - Showing
IntegrityErrortext to members instead of a message from validation. - Making a validator the only guard for a rule the database could hold.
Follow-up the interviewer might ask:
- “Which of
save(),update(), andbulk_create()callfull_clean()?” - “Where would you catch
IntegrityErrorin a view, and what would you show the member?”
L2 (Mid-Level): Why does save() not call full_clean(), and when should your code call it?
What the interviewer is testing: Do you understand the cost and the order of model validation, and who is responsible for calling it?
Flip to check your answerFold answer back

Perfect answer: Validation costs work: validate_unique() and validate_constraints() query the database, and validators can be slow. Django leaves the decision to the caller, so code that saves trusted data in bulk does not pay for it. full_clean() runs clean_fields(), then clean(), then validate_unique(), then validate_constraints(), and collects every error into one ValidationError whose message_dict maps each field, or __all__ for the whole row, to its messages. A field that already failed is excluded from the later checks that use it. Forms and the admin site call it for me. My own code should call it whenever data comes from a person or an outside source: an import, an API payload, a management command. Code that builds rows from values it controls can rely on the constraints. Because clean() may change values, such as lower-casing an email, I call full_clean() before save(), not after.
Behind the scenes:
clean_fields() -> each value, validators
clean() -> the row as a whole
validate_unique() -> unique fields (query)
validate_constraints() -> Meta.constraints (query)
all errors -> one ValidationErrorCode proof: one unsaved event with three problems, and the same values saved without validation, then rolled back:
from datetime import UTC, datetime
import setup_django
from django.core.exceptions import ValidationError
from django.db import transaction
from events.models import Event
fields = dict(title='', location='Leeds', capacity=0,
starts_at=datetime(2027, 2, 1, tzinfo=UTC),
ends_at=datetime(2027, 2, 1, 2, tzinfo=UTC),
timezone='Europe/Londn')
try:
Event(**fields).full_clean()
except ValidationError as error:
print(sorted(error.message_dict))
with transaction.atomic():
unchecked = Event(**dict(fields, capacity=5))
unchecked.save()
print('saved without validation:', unchecked.pk > 0)
transaction.set_rollback(True)
print(Event.objects.filter(location='Leeds').count())['__all__', 'timezone', 'title']
saved without validation: True
0The blank title and the time zone are field errors, and the capacity rule is a constraint error under __all__, all in one exception. With a valid capacity, save() stores the blank title and the misspelt time zone without complaint, until the rollback removes the row.
Common mistakes:
- Calling
full_clean()aftersave(), so its corrections never reach the database. - Expecting
full_clean()to stop at the first error. - Raising errors in
clean()for a field a form does not show, which Django reports as aValueError.
Follow-up the interviewer might ask:
- “How would you validate ten thousand imported rows efficiently?”
- “What does the
excludeargument offull_clean()do, and who uses it?”
L3 (Senior): How do you enforce “one active registration per member and event” without forbidding a new registration after a cancellation?
What the interviewer is testing: Can you choose the right kind of uniqueness, and explain why application checks are not enough?
Flip to check your answerFold answer back

Perfect answer: A check in the view, “is there an active registration? if not, create one”, has a gap between the check and the insert, and two simultaneous requests both pass it. So the rule must live in the database. A plain unique constraint on event and member would also refuse re-registering, because cancelled rows keep the same pair. The answer is a conditional UniqueConstraint(fields=['event', 'member'], condition=Q(status='active'), name=...), which PostgreSQL and SQLite build as a partial unique index holding only active rows. I give it a violation_error_message, so validation explains the duplicate, and I still handle IntegrityError in the view for the race the check cannot see. Tests prove both halves: a second active registration raises IntegrityError, and a registration after a cancellation succeeds. MySQL and MariaDB do not support conditions on unique constraints, so on those databases I would need another design, such as a nullable column that is unique only while active.
Behind the scenes:
UniqueConstraint(fields=['event', 'member'],
condition=Q(status='active'))
-> CREATE UNIQUE INDEX ... WHERE status = 'active'
cancelled rows -> outside the index
two active -> IntegrityErrorCode proof: the index as SQLite stores it, and a re-registration after a cancellation, rolled back:
import setup_django
from django.db import connection, transaction
from django.utils import timezone
from registrations.models import Registration
with connection.cursor() as cursor:
cursor.execute(
'SELECT sql FROM sqlite_master WHERE name = %s',
['registration_one_active'],
)
(sql,) = cursor.fetchone()
print('WHERE', sql.split(' WHERE ')[1])
place = Registration.objects.filter(status='active')[0]
with transaction.atomic():
place.status = 'cancelled'
place.cancelled_at = timezone.now()
place.save()
Registration.objects.create(event=place.event,
member=place.member)
print('registered again:', place.event)
transaction.set_rollback(True)WHERE "status" = 'active'
registered again: Python meetupsqlite_master is SQLite’s own table of tables and indexes, and holds the CREATE UNIQUE INDEX statement with its WHERE clause. Cancelling a place and registering again succeeds, and the rollback restores the original row.
Common mistakes:
- Using
unique_together, which blocks re-registration after a cancellation. - Relying on an
exists()check in the view. - Forgetting that the same pattern fits organizer assignments, with
revoked_at__isnull=True.
Follow-up the interviewer might ask:
- “What does the member see if two clicks race, and where is that handled?”
- “How would you enforce the same rule on MySQL?”
L4 (Staff): You must add a constraint to a large production table that already holds rows breaking it. How do you roll it out?
What the interviewer is testing: Can you change a live schema without an outage, a failed deploy, or silently lost data? This looks ahead to Chapters 32 and 64.
Flip to check your answerFold answer back

Perfect answer: First I measure: a query that counts the rows breaking the rule, using the constraint’s own condition, tells me how big the problem is. Then I stop new bad rows at the source, by deploying validation and fixing the code paths that create them, so the count stops growing. Next comes the data fix, decided with the people who own the data: correct, cancel, or delete each kind of row, in a reviewed, reversible data migration or command, never by hand in production. Only then do I add the constraint. On SQLite, Django rebuilds the table, which is fine for a small database. On PostgreSQL, adding a CHECK scans the whole table while holding a lock; for a large table I add it as NOT VALID, which checks only new writes, and run VALIDATE CONSTRAINT afterwards, which checks old rows without blocking writes. A unique index can be built with CREATE INDEX CONCURRENTLY. Chapter 64 covers these zero-downtime patterns. After release, I watch for IntegrityError in the logs: it shows a path I missed.
Behind the scenes:
count -> exclude(constraint.condition).count()
stop -> validation and code fixes first
fix -> reviewed data migration
add -> PostgreSQL: NOT VALID, then VALIDATE
watch -> IntegrityError in the logsCode proof: every CheckConstraint on Event, used to count the rows that would break it:
import setup_django
from django.db.models import CheckConstraint
from events.models import Event
for constraint in Event._meta.constraints:
if isinstance(constraint, CheckConstraint):
broken = Event.objects.exclude(constraint.condition)
print(constraint.name, broken.count())event_capacity_gt_0 0
event_ends_after_start 0
event_status_valid 0_meta.constraints is the model’s list of constraints, and each CheckConstraint keeps its condition as a Q object, so exclude() finds the rows outside it. All three counts are 0 now; before Step 6’s fixes, the first would have been 1.
Common mistakes:
- Adding the constraint first and discovering the bad rows when the deploy fails.
- Fixing production rows by hand, with no record or review.
- Locking a busy table for minutes with a plain
ADD CONSTRAINTon PostgreSQL.
Follow-up the interviewer might ask:
- “How would you make the data fix reversible?”
- “What does
NOT VALIDguarantee beforeVALIDATEruns?”
L5 (Lead): Design email identity for an international product. What does “the same address” mean, and where do you enforce it?
What the interviewer is testing: Can you turn a vague identity question into a product decision, and know the limits of the tools that enforce it? This looks ahead to Chapters 27 and 32.
Flip to check your answerFold answer back

Perfect answer: “The same address” is a product decision, not a technical default. Domains are case-insensitive, and the local part before @ is case-sensitive in principle but treated as case-insensitive by nearly every provider, so most products treat addresses that differ only in case as one identity. I decide whether to store addresses as typed and compare them case-insensitively, or to store a normalized form; Otahque stores lower case. Then I enforce it everywhere: one normalization function in the user manager, used for creation and for the sign-in lookup; normalization in clean() for forms; and a database constraint for writes that skip both. International addresses need more care. Python’s lower() handles every alphabet, but SQLite’s LOWER() changes only A to Z, so a SQLite constraint misses É, while PostgreSQL’s lower() handles it. Some letters have no simple lower-case pair, such as German ß, where casefold() gives ss, and visually identical characters can have different Unicode codes, so I would also normalize to one Unicode form and decide whether such addresses may register at all. I record the decision, and test sign-up, sign-in, and imports against it.
Behind the scenes:
decide -> same address = same member
normalize -> manager: create_user(), sign-in lookup
validate -> clean() for forms
enforce -> CHECK email = LOWER(email)
limits -> SQLite LOWER(): A to Z onlyCode proof: the same address lower-cased by SQLite and by Python:
import setup_django
from django.db import connection
address = 'ÉMILE@EXAMPLE.ORG'
with connection.cursor() as cursor:
cursor.execute('SELECT LOWER(%s)', [address])
print('SQLite:', cursor.fetchone()[0])
print('Python:', address.lower())
print('Straße:', 'Straße'.lower(), 'Straße'.casefold())SQLite: Émile@example.org
Python: émile@example.org
Straße: straße strasseSQLite leaves É in capitals, so a direct write of Émile@example.org would pass Otahque’s constraint on SQLite; the manager’s Python lower() handles it. casefold() is Python’s stronger comparison form, which turns ß into ss.
Common mistakes:
- Normalizing at sign-up but not at sign-in, so a member cannot sign in with capitals.
- Assuming the database’s
LOWER()matches Python’slower(). - Treating the decision as a technical detail instead of recording it.
Follow-up the interviewer might ask:
- “Would you store the address as typed as well, for display?”
- “How do you migrate existing accounts that collide after normalization?”
Next: Chapter 22 composes queries: QuerySet methods, custom managers, Q objects combined with &, |, and ~, and F expressions that compare one field with another.
Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)
PAGE 006Found an error or something unclear? Report an issue with this chapter (GitHub, opens in a new tab)