Complete six-part pre-release for review. Adds psycopg 3.3.9 and no migration. Checked on Windows with PostgreSQL 18.3 server programs; the macOS and Linux installs are not yet verified. Locking the last place follows in Chapter 33, Docker in 62, and several databases at once in 67.
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 THIRTY-TWO
Moving to PostgreSQL
Stage 4: Accounts and first release (Chapters 24 to 34)
Prerequisites: Chapters 15 to 31, including the Chapter 31 project and its 342 passing tests, the migrations and data migrations of Chapters 18 to 31, the Organizers and Administrators groups made by Chapter 30’s migration, two-factor sign-in from Chapter 29, the settings read through python-decouple since Chapter 8, and the uv workflow from Chapter 4
What you’ll build: Otahque running on PostgreSQL 18 with every member, event, place, and two-factor setting moved across and checked table by table; settings that choose the database from .env; a test suite that runs on PostgreSQL and sorts text the same way on every computer; a backup that has been restored and compared; a record of the decision; and wider, two-column forms
Why This Matters
Chapter 31 ended with a promise it could not keep. Sam’s clinic has one place left, and Sai and Soni press Register in the same instant. Each request counts the places, sees one, and inserts a row: the clinic now holds one person more than its room. On SQLite the problem cannot even be shown, because SQLite lets only one connection write at a time and has no way to lock a single row. Chapter 33 must prove that Otahque gives the last place to exactly one of them, and for that it needs a database that serves many connections at once and can lock a row while one request decides.
That database is PostgreSQL. Moving to it is not only a change of setting. Everything readers have made since Chapter 18 lives in db.sqlite3: Sam’s events and his two-factor app, Sai’s phone number, Raj’s late cancellation, Soni’s account. All of it must arrive intact, and “it looks fine” is not proof. A careful move copies the data, counts and compares it on both sides, and keeps the old file until the new database has been checked.
A server database also brings duties that a file never had: a password to keep out of Git, a program to install and start, a backup that is worth nothing until it has been restored once, and copies of personal data that must not be left lying around. This chapter takes them one at a time.
By the end of the chapter, you will be able to:
explain what a database server offers that a single file cannot, and why Otahque needs it before Chapter 33;
install PostgreSQL 18, create a role and a database, and connect Django to it through settings read from .env;
move existing data between two database engines without losing rows, ids, or times, and prove it with a comparison;
make the test suite run on PostgreSQL, with text sorted the same way on every computer;
make a backup with pg_dump, restore it into a copy, and compare the two;
record the decision in an ADR, with what it costs and when to revisit it.
Out of scope: locking the last place (Chapter 33), running the database in a container (Chapter 62), scheduled backups and retention (Chapter 65), connection pooling (Chapter 66), search (Chapter 56), and several databases at once (Chapter 67). An optional lab at the end of How We Build It reads a table that Otahque does not own.
Since Chapter 18 Django has opened db.sqlite3 itself, as a file, whenever it needed data. SQLite is excellent for that: nothing to install, nothing to start, and one file to copy. Its limits appear when several things happen at once. A write takes a lock on the whole file, so a second writer waits or fails, and there is no way to say “lock this one event row while I count its places”. Figure 32.1 sets the two side by side.
Figure 32.1 — One file that one process writes, against a server that many connections share.
New Concept: a database server
What problem exists? Otahque must handle requests that arrive together, and the database must decide between them: who got the last place, and who must wait.
What did people do before? A file database such as SQLite serves one writer at a time. That is enough for one person developing, and not for a website at a busy moment.
What is it? A database server is a program that runs on its own, owns the data files, and answers clients over connections. Django becomes one client among others, such as psql, the command-line client, or a backup program. The server checks who is asking: each client signs in as a role, a database user with a password and permissions, and asks for one database, a named set of tables. The server listens on a port, 5432 by default.
Why use it? Many connections at once, row locks, and one place that enforces every rule for every client.
Now let’s use it. Step 2 installs PostgreSQL, and Step 3 creates the role and the database that Otahque signs in to.
A role is not an Otahque member. Sam signs in to Otahque with his email address, and Otahque signs in to PostgreSQL as the role otahque. Members never see the database, and the database never sees their passwords, only the hashes Django stores.
PostgreSQL 18 and psycopg
PostgreSQL releases a new major version every autumn and supports each for five years. Django 6.1 needs PostgreSQL 15 or later and, to talk to it, a driver: a Python package that speaks the server’s protocol. Django recommends psycopg 3.
New Tool: PostgreSQL and psycopg
What problem exists? Otahque needs a database server that Django supports, that runs on Windows, macOS, and Linux, and that every hosting service offers.
What did people do before? Commercial servers with licences, or MySQL, which Django also supports. Many Django projects start on SQLite and move later, as Otahque does now.
What is it? PostgreSQL is a free, open-source database server, developed by a community since 1996, with strict handling of types and constraints and many index types. psycopg is the PostgreSQL driver for Python; its binary package carries a ready-built copy of libpq, PostgreSQL’s client library, so nothing has to be compiled.
Why use it? It is the database most Django projects use in production, Django’s PostgreSQL support is the most complete, and Chapter 33 needs its row locks. psycopg 3 is the driver Django recommends, and Chapter 66 needs it for connection pooling.
Now let’s use it. Step 2 installs PostgreSQL 18; Step 5 adds psycopg[binary] to the project at an exact version.
The user decided to use PostgreSQL 18, not 19. Version 19 was released on 19 November 2026, three days before this chapter was checked, and hosts, installers, and the official container image take time to offer a new major version. Version 18 is supported until November 2030. Table 32.1 lists the versions this chapter pins.
Table 32.1 — The versions in this chapter
Part
Version
Why
PostgreSQL
18 (18.7 newest on 22 Nov 2026)
Supported to 2030; 19 is days old
psycopg
3.3.9, binary package
Recommended by Django
Django
6.1.2 (minimum PostgreSQL 15)
Unchanged
The binary package is right for developing. For a production server, psycopg’s documentation prefers a build against the system’s own libpq, which security updates then reach; Chapter 62 makes that choice.
Moving data between two engines
Two kinds of rows live in Otahque’s database. Some were made by migrations: the content types that name each model (Chapter 23’s admin and Chapter 30’s permissions use them), the permissions Django creates for each model, and the Organizers and Administrators groups from Chapter 30’s data migration. Others were made by people: members, events, places, profiles, two-factor settings, and the audit trail. The first kind appears again by itself when you run migrate on the new database. Only the second kind needs moving.
Django’s dumpdata command writes rows out as a file, and loaddata reads them back into any database Django supports. Two things make the move work between engines:
Exclusions. Rows that migrations make again are left out of the file. If they were included, loading them would collide with the ones migrate just made: same name, different number.
Natural keys. A permission is 25 in one database and 34 in the other, but “events, add_event” in both. With --natural-foreign, a row that points at a permission, a content type, a group, or a member writes the name, and loaddata looks up the new number. Rows keep their own ids, so addresses such as /events/7/ stay the same.
Natural keys have a second option, --natural-primary, which leaves a row’s own id out of the file when the model has a natural key. Members have one, their email address. In Interview Question L4 you will see what that does to Soni.
Under the Hood: what loaddata does, and why the file is XML
loaddata reads the file and saves each object in raw form, skipping your models’ own save() methods, all in one transaction, so a failure leaves nothing half loaded. Rows that point at each other are fine, because PostgreSQL checks the foreign keys only when the transaction ends. Then it resets each table’s sequence, the counter PostgreSQL uses to hand out the next id, to just above the highest id loaded. Without that step, the next event Sam creates would be given id 1, which is taken. The file format matters too. Django’s JSON format writes times to the thousandth of a second, so 18:30:00.892481 becomes 18:30:00.892: every registration and cancellation time would change slightly, and a cancellation made in the same millisecond as its deadline could stop counting as late. The XML format writes all six digits, so this chapter uses XML.
Text order and collation
Ask a database to sort “apple day”, “Zebra talk”, and “Émile meets” and you may get three different answers. The rules for comparing text are called a collation. SQLite compares the numbers of the characters, their Unicode code points: capital letters (Z is 90) come before small ones (a is 97), and accented letters (É is 201) after both. PostgreSQL normally uses the collation of the computer it was installed on, so the same rows may sort one way on Windows and another on macOS, and differently again on the computer that runs the tests in Chapter 34.
New Concept: one sort order everywhere
What problem exists? Lists that Otahque sorts by text, such as the admin’s members by email address, and later search results and name lists, must come out the same for every reader and in every test run.
What did people do before? They accepted each computer’s collation and found the difference when a test passed on one machine and failed on another.
What is it? PostgreSQL 17 added a builtin collation provider that does not depend on the operating system. Its C.UTF-8 collation sorts by code point, exactly as SQLite does, on every platform.
Why use it? Otahque’s behaviour does not change in the move, and tests give one answer everywhere. Sorting names the way a language expects is a separate need, which Chapter 61 can meet column by column if other languages arrive.
Now let’s use it. Step 3 creates the database with C.UTF-8, and Step 9 makes the test database use it too.
Table 32.2 collects the differences between the two databases that matter to Otahque today.
Table 32.2 — What changes for Otahque on PostgreSQL
Topic
SQLite
PostgreSQL in this chapter
Writers at once
One
Many connections
Row locks
None
select_for_update() (Chapter 33)
Text order
By code point
By code point (C.UTF-8)
contains lookups
Ignore case for A to Z
Respect case; use icontains
Test database
A file, made freely
Needs the role's CREATEDB right
Times in a dump
Not used before
Kept to the microsecond in XML
One difference you might expect does not matter: the wording of database errors. Chapter 31’s register() never reads the message of an IntegrityError; it checks whether the member’s place exists. That is why all 342 tests pass on PostgreSQL unchanged.
A backup is proved by a restore
PostgreSQL’s own tool pg_dump writes a whole database to one file, and pg_restore reads it back. A backup that has never been restored proves nothing: the file may be empty, incomplete, or unreadable by the version you have. The habit this chapter starts is a restore rehearsal: restore into a new database, compare it with the original, then remove the copy. Chapter 65 schedules backups and Chapter 62 repeats the rehearsal with a container.
dumpdata and pg_dump have different jobs. dumpdata writes rows in a form any engine can read, which is what a one-off move between SQLite and PostgreSQL needs. pg_dump writes everything PostgreSQL holds, including indexes, constraints, and sequences, which is what a backup of PostgreSQL needs.
In practice: copies of personal data
Situation. The move file and the backup both hold every member’s email address, password hash, and phone number, and the two-factor secrets that Chapter 29 stores as plain text.
Application. Write them outside the project folder, so Git never sees them, and delete them as soon as they have done their job. Keep db-before-32.sqlite3 only until you trust the new database.
Consideration. Deleting a file is not destroying it: backups of your computer or a cloud folder may still hold a copy. Chapter 59 encrypts the two-factor secrets, and Chapter 65 decides how long Otahque keeps data at all.
Try it yourself
Que. 1 Sam’s events have ids 1, 2, 3, 5, 6, 7, and 8; event 4 was deleted in Chapter 19. After the move, what id does PostgreSQL give the next event Sam creates, and why?
Flip to check your answerFold answer back
Answer. 9. loaddata keeps each row’s id and then resets the sequence to just above the highest id it loaded. The gap at 4 stays a gap: ids are never reused, so an old link to event 4 cannot open a different event.
Que. 2 You dump with the JSON format instead of XML. What would the comparison script report, and would anyone notice otherwise?
Flip to check your answerFold answer back
Answer. It would report that the tables with times differ, such as events, members, and registrations, because each time lost its last three digits. Nobody would notice on a page, which shows minutes. That is exactly why the move is checked by comparing rows, not by looking at pages.
Start from Chapter 31, in the folder containing manage.py, with your own .env, the locked environment, 342 passing tests, every migration applied, and the work committed. This chapter installs PostgreSQL 18 and adds one package, psycopg. The new files are compare_databases.py beside manage.py and docs/adr/ADR-005-postgresql.md; config/settings.py, .env, .env.example, .gitignore, check_environment.py, events/tests.py, and seven templates and the stylesheet source change. The visible result is the same Otahque, with all its data, now served from PostgreSQL, and wider forms. Commands that differ between systems are labelled; the chapter’s checks ran in Windows PowerShell 5.1 and Git Bash, against PostgreSQL 18.3 server programs.
The Custom Way
The obvious way to move data is to read each table from SQLite and insert the same rows into PostgreSQL yourself. The practice file below does that for events. It is shown to explain what Django’s tools do for you; you do not need to run it, and it was run once against a separate, empty database:
s_by_hand.py (illustration only)
"""Copy events by hand, to see what loaddata does for us."""
import sqlite3
from django.db import IntegrityError, connection, transaction
from events.models import Event
old = sqlite3.connect('db-before-32.sqlite3')
cursor = old.execute('SELECT * FROM events_event')
names = [column[0] for column in cursor.description]
rows = [dict(zip(names, row)) for row in cursor]
print('SQLite starts_at:', repr(rows[0]['starts_at']))
print('SQLite phone_required:', repr(rows[0]['phone_required']))
columns = ', '.join(names)
marks = ', '.join(['%s'] * len(names))
sql = f'INSERT INTO events_event ({columns}) VALUES ({marks})'
with connection.cursor() as pg:
try:
with transaction.atomic():
pg.execute(sql, list(rows[0].values()))
except Exception as error:
print('as it is:', str(error).splitlines()[0])
for row in rows:
row['phone_required'] = bool(row['phone_required'])
pg.execute(sql, list(row.values()))
print('copied events:', Event.objects.count())
new = Event.objects.first()
new.pk = None
try:
with transaction.atomic():
new.save()
except IntegrityError as error:
print('a new event:', str(error).splitlines()[0])
Output
SQLite starts_at: '2026-11-19 18:30:00'
SQLite phone_required: 0
as it is: column "phone_required" is of type boolean but
expression is of type integer
copied events: 7
a new event: duplicate key value violates unique constraint
"events_event_pkey"
Three problems in a few lines. SQLite stores times as text and true or false as 0 or 1, while PostgreSQL has real types and refuses 0 for a boolean: every column has to be translated. The rows went in with their ids, but PostgreSQL’s counter for new ids still stood at 1, so the next event Sam creates collides with an existing one. And this is one table: members, places, and permissions point at each other by number, and those numbers differ on each side. The Django Way leaves translation to dumpdata and loaddata, which know every field’s type, reset the counters, and follow relations by name.
The Django Way
The move runs in the order that Figure 32.2 shows. Steps 1 to 3 prepare, Step 4 writes the file, Steps 5 to 7 connect Django to PostgreSQL, and Step 8 loads and checks.
Figure 32.2 — The move, in order, with what is left out and why.
Step 1: Check the starting point and keep a copy
Run the whole suite. From this chapter on, the whole suite runs with --parallel, which starts one test process per processor core, each with its own test database:
Terminal
uv run python manage.py test --parallel
Output
Found 342 test(s).
Creating test database for alias 'default'...
...
Ran 342 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Add registration, cancellation, and attendees
Now keep a copy of the database that nothing will change. Stop runserver first if it is running.
The copy holds personal data, so Git must never see it. Add these lines at the end of .gitignore:
.gitignore (add at the end)
# The SQLite copy kept from before Chapter 32
db-before-32.sqlite3
git status --short prints nothing: the copy is ignored and the project is unchanged.
Step 2: Install PostgreSQL 18
Install the newest PostgreSQL 18 for your system. Each installer also installs the command-line programs psql, createdb, pg_dump, and pg_restore, which this chapter uses.
Windows. From the PostgreSQL download page for Windows, run the installer for version 18. Keep “PostgreSQL Server” and “Command Line Tools”; pgAdmin and Stack Builder are optional. Choose a password for the postgres administrator and store it in your password manager. Keep port 5432 and the default locale.
macOS. Install Postgres.app with PostgreSQL 18 and follow its page for adding the command-line tools to your PATH, or use Homebrew: brew install postgresql@18, then brew services start postgresql@18, and put $(brew --prefix postgresql@18)/bin on your PATH.
Linux (Debian, Ubuntu). Add the PostgreSQL project’s repository with sudo apt install -y postgresql-common and sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh, then run sudo apt install postgresql-18. The server starts by itself.
The installer runs PostgreSQL as a background service that starts with the computer, so nothing needs to be started by hand.
Common Error: psql is not recognized
On Windows, the installer does not add its programs to PATH. A new terminal then answers:
Output
psql : The term 'psql' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included,
verify that the path is correct and try again.
Add C:\Program Files\PostgreSQL\18\bin to your user’s Path in Windows’ Environment Variables settings, and open a new terminal, which reads the new Path. On macOS, open a new terminal after following Postgres.app’s or Homebrew’s PATH instructions.
To use the programs in the current window while you fix Path for good:
Any 18 is right; your last number may be higher. The checks for this chapter ran on 18.3, and 18.7 was the newest on 22 November 2026.
Step 3: A role and a database for Otahque
Otahque gets its own role, so the administrator’s password never goes in its settings. Sign in to PostgreSQL as the administrator; how depends on your system, as Table 32.3 shows.
Table 32.3 — Opening psql as the administrator
System
Command
Windows
psql -h localhost -U postgres (the installer's password)
macOS
psql -h localhost -d postgres (you are the administrator)
Linux
sudo -u postgres psql
On Windows:
Terminal
psql -h localhost -U postgres
At the postgres=# prompt, type:
psql, as the administrator
CREATE ROLE otahque LOGIN CREATEDB;
\password otahque
\q
CREATE ROLE makes a role that may sign in (LOGIN) and create databases (CREATEDB), which the test runner needs in Step 9. \password asks for the new password twice without showing it, and sends only its hash, so it never lands in your shell history. Choose a new password, not one you use elsewhere, and keep it for .env. \q leaves psql.
Now create the database, owned by otahque, with the code-point sort order. The command is split; in PowerShell the backtick continues it, with no space after it:
On macOS leave out -U postgres in the first command; on Linux start it with sudo -u postgres and leave out -h localhost -U postgres. Each program asks for the password of the role it signs in as. -T template0 builds the database from PostgreSQL’s untouched template, which is required when the new database’s sort order differs from the server’s default. The second command signs in as otahque and lists the database:
Output
List of databases
-[ RECORD 1 ]-----+---------------------------
Name | otahque
Owner | otahque
Encoding | UTF8
Locale Provider | builtin
Collate | English_United States.1252
Ctype | English_United States.1252
Locale | C.UTF-8
ICU Rules |
Access privileges |
-x prints one field per line. Look for builtin on the Locale Provider line and C.UTF-8 on the Locale line. Collate and Ctype show the server’s own default, which a database with the builtin provider does not use for sorting. Typing the password for every command soon becomes tiring. psql and the other programs can read it from a password file: on Windows %APPDATA%\postgresql\pgpass.conf, elsewhere ~/.pgpass with permissions 600, one line localhost:5432:*:otahque:yourpassword. It is a secret like .env; use it only on your own computer.
Step 4: Write the data out of SQLite
Django still reads SQLite, so this is the moment to write the data out. The command leaves out the four kinds of rows that migrations make again or that should not move, follows relations by name, and writes XML to a file one folder up, outside the project:
The command prints nothing when it succeeds. ../otahque-data.xml now holds your members, events, places, profiles, email addresses, two-factor settings, organizer assignments, audit rows, and the admin’s history. Group memberships travel with each member, as group names.
Common Error: ’charmap’ codec can’t encode character
Without -X utf8, Python on Windows writes files in the computer’s old code page, which has no room for many characters. One Hindi word in an event description is enough:
Output
CommandError: Unable to serialize database: 'charmap' codec
can't encode characters in position 43-48: character maps
to <undefined>
A half-written file is left behind. Delete it and run the command again with -X utf8, which makes Python write UTF-8. macOS and Linux already use UTF-8; the option does no harm there.
Step 5: Add the driver
Add psycopg at the exact version checked for this chapter:
Terminal
uv add "psycopg[binary]==3.3.9"
Output
Resolved 25 packages in 13ms
Installed 2 packages in 87ms
+ psycopg==3.3.9
+ psycopg-binary==3.3.9
uv records the package in pyproject.toml, locks it and psycopg-binary in uv.lock, and installs both. Nothing uses them yet.
Step 6: Choose the database from .env
The settings have named one SQLite file since Chapter 6. Replace the whole Database section of config/settings.py, from the # Database comment to the closing brace of DATABASES, with:
config/settings.py (replace the Database section)
# Database
# https://docs.djangoproject.com/en/6.1/ref/settings/#databases
# SQLite until DB_ENGINE names another backend, such as
# PostgreSQL from Chapter 32 (docs/adr/ADR-005-postgresql.md).
SQLITE = 'django.db.backends.sqlite3'
# An empty DB_ENGINE line in .env also means SQLite.
DB_ENGINE = config('DB_ENGINE', default='') or SQLITE
if DB_ENGINE == SQLITE:
DATABASES = {
'default': {
'ENGINE': SQLITE,
'NAME': BASE_DIR / 'db.sqlite3',
}
}
else:
try:
DATABASES = {
'default': {
'ENGINE': DB_ENGINE,
'NAME': config('DB_NAME'),
'USER': config('DB_USER'),
'PASSWORD': config('DB_PASSWORD'),
'HOST': config('DB_HOST', default='localhost'),
'PORT': config('DB_PORT', default='5432'),
}
}
except UndefinedValueError as error:
raise ImproperlyConfigured(
f'{error} See .env.example.'
) from None
With DB_ENGINE missing or empty, nothing changes: Django uses SQLite, as every earlier chapter’s checkpoint expects. With DB_ENGINE set, the other five values are read, and a missing one stops Django with a message naming it, as a missing secret key has since Chapter 8. Add the six names, without the password, at the end of .env.example:
.env.example (add at the end)
# The database (Chapter 32). Leave DB_ENGINE empty for
# SQLite; for PostgreSQL set it and the five values below.
DB_ENGINE=
DB_NAME=otahque
DB_USER=otahque
DB_PASSWORD=
DB_HOST=localhost
DB_PORT=5432
And the real values at the end of your own .env, which Git ignores:
.env (add at the end)
DB_ENGINE=django.db.backends.postgresql
DB_NAME=otahque
DB_USER=otahque
DB_PASSWORD=the password you chose in Step 3
DB_HOST=localhost
DB_PORT=5432
Put the password you chose in Step 3 after DB_PASSWORD=. Then let check_environment.py, the helper from Chapter 4, also say which database is in use. Replace the file with:
check_environment.py
"""Show the Python, environment, Django, and database in use."""
import os
import sys
import django
def database():
"""Return the database Django uses here, and its version."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'config.settings')
django.setup()
from django.db import connection
with connection.cursor() as cursor:
if connection.vendor == 'postgresql':
cursor.execute('SHOW server_version')
else:
cursor.execute('SELECT sqlite_version()')
return f'{connection.vendor} {cursor.fetchone()[0]}'
print(sys.version.split()[0])
print(sys.executable)
print(sys.prefix != sys.base_prefix)
print(django.get_version())
print(database())
The last line is the proof that Django now talks to PostgreSQL, not to SQLite. Run this check whenever you are unsure which database a terminal is using.
Common Error: password authentication failed
A wrong password in .env, or a role name that does not match, ends in:
Output
psycopg.OperationalError: connection failed: connection to
server at "127.0.0.1", port 5432 failed: FATAL:
password authentication failed for user "otahque"
Compare DB_USER and DB_PASSWORD with Step 3. To set a new password, sign in as the administrator and run \password otahque again. If the message says the connection was refused instead, the server is not running or listens on another port: check DB_PORT and the service.
Step 7: Create the tables on PostgreSQL
The new database is empty. migrate runs every migration since Chapter 18 against it:
Terminal
uv run python manage.py migrate
Output
Operations to perform:
Apply all migrations: account, accounts, admin, audit,
auth, contenttypes, events, mfa, registrations, sessions,
socialaccount
Running migrations:
Applying contenttypes.0001_initial... OK
...
Applying socialaccount.0004_app_provider_id_settings... OK
Applying socialaccount.0005_socialtoken_nullable_app... OK
Applying
socialaccount.0006_alter_socialaccount_extra_data... OK
Chapter 30’s data migration ran with the others, so the Organizers and Administrators groups already exist, with their permissions. So do the content types and permissions, with new ids: these are the rows Step 4 left out.
Step 8: Load the data and compare
The comparison is a small program of its own, kept in the project so that Chapter 62 can use it again. Create compare_databases.py beside manage.py:
compare_databases.py
"""Compare Otahque's database with a copy, table by table.
Run: uv run python compare_databases.py OTHER
OTHER is a SQLite file, such as db-before-32.sqlite3, or the
name of another PostgreSQL database on the same server.
"""
import os
import sys
import django
from django.conf import settings
# Rows that migrations make again, with new ids.
REMADE = {'contenttypes.contenttype', 'auth.permission',
'auth.group', 'auth.group_permissions'}
# Rows left behind on purpose.
NOT_MOVED = {'sessions.session': 'everyone signs in again'}
def other_database(name):
"""Return settings for the database to compare with."""
if name.endswith('.sqlite3'):
return {'ENGINE': 'django.db.backends.sqlite3',
'NAME': settings.BASE_DIR / name}
return {**settings.DATABASES['default'], 'NAME': name}
def value(obj, field):
"""Return a field's value; a related row by natural key."""
if field.is_relation:
related = getattr(obj, field.name)
if hasattr(related, 'natural_key'):
return related.natural_key()
return field.value_from_object(obj)
def rows(model, alias, limit):
"""Return up to limit rows of a model, as tuples."""
remade = (model._meta.label_lower in REMADE
or model._meta.auto_created)
fields = [f for f in model._meta.concrete_fields
if not (remade and f.primary_key)]
found = [tuple(value(obj, f) for f in fields)
for obj in model._default_manager.using(alias)
.order_by('pk')[:limit]]
return sorted(found, key=repr) if remade else found
def main():
"""Print one line per table; return how many differ."""
from django.apps import apps
from django.db import connections
here = connections['default']
print(f'here: {here.vendor} {here.settings_dict["NAME"]}')
print(f'other: {sys.argv[1]}')
differ = 0
for model in apps.get_models(include_auto_created=True):
label = model._meta.label_lower
table = model._meta.db_table
if label in NOT_MOVED:
print(f'skip {table}: {NOT_MOVED[label]}')
continue
a = model._default_manager.using('default').count()
b = model._default_manager.using('other').count()
# Ten rows each, or every row that migrations remake.
limit = 10 if label not in REMADE else None
same = a == b and (rows(model, 'default', limit)
== rows(model, 'other', limit))
differ += not same
mark = 'ok ' if same else 'DIFF'
print(f'{mark} {table}: {a} / {b}')
print('every table matches' if not differ
else f'{differ} table(s) differ')
return differ
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'config.settings')
# Add the second database before Django reads the list.
settings.DATABASES['other'] = other_database(sys.argv[1])
django.setup()
sys.exit(1 if main() else 0)
For every model, including the hidden tables behind many-to-many fields, the script counts the rows in both databases and compares the first ten, field by field. Rows that migrations made again have different ids on each side, so it compares those by natural key instead, and every one of them, so a group that lost a permission would show. Sessions are skipped on purpose. Now load and compare:
Terminal
uv run python manage.py loaddata ../otahque-data.xml
uv run python compare_databases.py db-before-32.sqlite3
Output
Installed 28 object(s) from 1 fixture(s)
here: postgresql otahque
other: db-before-32.sqlite3
ok django_admin_log: 1 / 1
ok auth_permission: 66 / 66
ok auth_group_permissions: 14 / 14
ok auth_group: 2 / 2
ok django_content_type: 17 / 17
skip django_session: everyone signs in again
ok accounts_user_groups: 0 / 0
ok accounts_user_user_permissions: 0 / 0
ok accounts_user: 4 / 4
ok accounts_profile: 1 / 1
ok events_event: 7 / 7
ok events_organizerassignment: 2 / 2
ok registrations_registration: 6 / 6
ok audit_auditevent: 1 / 1
ok account_emailaddress: 4 / 4
ok account_emailconfirmation: 0 / 0
ok socialaccount_socialapp: 0 / 0
ok socialaccount_socialaccount: 0 / 0
ok socialaccount_socialtoken: 0 / 0
ok mfa_authenticator: 2 / 2
every table matches
Every table matches. Start the development server and sign in as Sam: Otahque asks for his two-factor code, because his authenticator moved with him. Everyone else is signed out once, since sessions stayed behind. Create a draft event as Sam: its address uses the next number after the highest event id, because loaddata reset the sequence. Delete the draft from its page afterwards. Then delete the move file, which has done its job:
Keep db-before-32.sqlite3 until you have used the new database for a while; it is ignored by Git and changes nothing.
Step 9: Run the tests on PostgreSQL
Running the tests now creates a test database on the server, test_otahque, and removes it afterwards. Before the whole suite, one new test: text must sort by code point, as it did on SQLite. Add at the end of events/tests.py:
events/tests.py (add at the end)
class SortOrderTests(TestCase):
"""Text sorts the same way on every database and computer."""
def test_titles_sort_by_code_point(self):
for title in ('apple day', 'Zebra talk', 'Émile meets'):
save_event(title=title)
titles = Event.objects.order_by('title').values_list(
'title', flat=True
)
self.assertEqual(
list(titles),
['Zebra talk', 'apple day', 'Émile meets'],
)
Within a step, run only the tests you are working on:
Terminal
uv run python manage.py test events -k SortOrder
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
FAILED (failures=1)
It fails, although the otahque database sorts by code point. The test database is not a copy of it: Django asks PostgreSQL for a new database, and PostgreSQL copies its standard template, which has the server’s default sort order. The fix is a template of Otahque’s own, empty and with the right sort order:
Then tell Django to build the test database from it. In config/settings.py, below the 'PORT' line, add the TEST entry:
config/settings.py (in DATABASES, after 'PORT')
'PORT': config('DB_PORT', default='5432'),
# Tests copy this empty database, so they sort
# text as Otahque's own database does.
'TEST': {'TEMPLATE': 'otahque_template'},
TEST['TEMPLATE'] is a PostgreSQL setting: the template the test database is copied from. Leave otahque_template empty, and do not keep a psql session open in it, because PostgreSQL will not copy a database while someone is connected.
Terminal
uv run python manage.py test events -k SortOrder
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
Common Error: permission denied to create database
If the role was created without CREATEDB, every test run stops before the first test:
Output
Got an error creating the test database: permission denied to
create database
Sign in as the administrator and run ALTER ROLE otahque CREATEDB;. The role needs this right only to make and remove test databases; Chapter 63 gives the production role far less.
Now the whole suite, as at every checkpoint:
Terminal
uv run python manage.py test --parallel
Output
Found 343 test(s).
Creating test database for alias 'default'...
...
Ran 343 tests in ...s
OK
All 343 tests pass on PostgreSQL, 342 of them unchanged since Chapter 31. On a server database the suite takes about twice as long as on SQLite when run in one process, because every test talks to the server over a connection; --parallel more than wins that back. Confirm that no model change is waiting for a migration:
Terminal
uv run python manage.py makemigrations --check --dry-run
Output
No changes detected
Step 10: A backup, restored and compared
Make a backup of the live database in PostgreSQL’s own format, restore it into a new database built from the empty template, and compare the two with the same script. Figure 32.3 shows what each part proves.
Figure 32.3 — A backup proves nothing until a restore has been compared.
here: postgresql otahque
other: otahque_restore
ok django_admin_log: 1 / 1
...
ok mfa_authenticator: 2 / 2
every table matches
-F c writes PostgreSQL’s compressed custom format, which pg_restore reads. --no-owner makes the signed-in role own the restored tables. The restore matches. Now remove the copy and the file, never the live database:
Read the dropdb line twice before pressing Enter: it names otahque_restore.
Step 11: Wider pages and forms
Since Chapter 14 every page has been held to a column 672 pixels wide, so on a laptop most of the screen stays empty, and the event form is a long single column of thirteen fields with a button stretched across it. This chapter’s change to the interface is shared by every page: a wider column, forms in two columns on wider screens, buttons at their natural width, and a side panel on the account pages, where Cancel no longer looks like the main button.
In templates/base.html, replace the <main> line with:
The column grows with the window up to 1152 pixels, and the side margins grow on larger screens. In the same file, wrap the content block in a block named page, so that a layout can put something beside the content:
Two shared rules go in static/otahque/source.css, in the components layer after the .site-nav :focus-visible rule:
static/otahque/source.css (in @layer components, at the end)
/* A form's fields in two columns on wider screens; long
text, check boxes, and the form's errors take a row. */
.form-grid {
display: grid;
gap: 0.25rem 1.5rem;
}
@media (width >= 48rem) {
.form-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.form-grid > :has(textarea, .checkbox),
.form-grid > .errorlist {
grid-column: 1 / -1;
}
}
/* A form's buttons side by side, at their natural width. */
.form-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.75rem;
}
:has() picks the field wrappers that hold a text area or a check box, so the description and “Ask for a phone number” take a whole row while short fields pair up. Help text under labels was pale; make it darker, in the utilities layer before the .errorlist rule:
static/otahque/source.css (in @layer utilities, before .errorlist)
In events/templates/events/form.html, replace the lines from {% csrf_token %} to the button with:
events/templates/events/form.html (inside the form)
{% csrf_token %}
<div class="form-grid">{{ form }}</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">
Save draft</button>
</div>
Make the same change in events/templates/events/edit.html and accounts/templates/accounts/profile.html, keeping each button’s own words, “Save changes” and “Save profile”. The account pages from django-allauth get the side panel. Replace templates/allauth/layouts/base.html with:
templates/allauth/layouts/base.html
{% extends "base.html" %}
{% block title %}{% block head_title %}{% endblock %} |
Otahque{% endblock %}
{% block page %}
<div class="grid items-start gap-6
lg:grid-cols-[minmax(0,40rem)_minmax(0,1fr)]">
<div class="space-y-4">
{% block content %}{% endblock %}
</div>
<aside class="card space-y-2 border border-base-300
bg-base-100 p-6 text-sm"
aria-labelledby="account-help">
<h2 id="account-help" class="font-semibold">
Your Otahque account</h2>
<p>One account for every event: register, see your
places under My registrations, and, if you
organize, manage your events.</p>
<p>Two-factor sign-in asks for a code from an app on
your phone after your password. Turn it on from
your profile.</p>
</aside>
</div>
{% endblock %}
In templates/allauth/elements/form.html, put the actions slot in a row:
templates/allauth/elements/form.html (the actions slot)
And in templates/allauth/elements/button.html, give the secondary buttons that allauth marks link or outline, such as Cancel, an outline. Replace the first line of the <button> tag with:
templates/allauth/elements/button.html (the button tag)
<button class="btn btn-primary
{% if 'link' in attrs.tags or 'outline' in attrs.tags %}
btn-outline{% endif %}"
Rebuild the stylesheet and run the tests of the two apps whose templates changed:
Terminal
npm run build
uv run python manage.py test events accounts --parallel
Output
Found 270 test(s).
Creating test database for alias 'default'...
...
Ran 270 tests in ...s
OK
Open the New event page at full width and with the browser’s device toolbar at 390 pixels. At full width the fields pair up in two columns, the description spans both, and Save draft sits at the left at its own width. At 390 pixels everything is one column and the page does not scroll sideways. On the two-factor page, Cancel is an outline beside the filled Sign In button, and the account panel sits beside the form, or below it on a phone.
Step 12: Record the decision and commit
The move is an architecture decision with alternatives and consequences, so it gets an ADR, the fifth. Create docs/adr/ADR-005-postgresql.md:
docs/adr/ADR-005-postgresql.md
# ADR-005: PostgreSQL as Otahque's database
## Status
Proposed, November 2026 (Chapter 32). The choices follow
the user's decisions of 22 November 2026 (Chapter 32
D32.1-D32.7); this record is not yet reviewed or accepted.
## Context
Since Chapter 18 Otahque has stored its data in SQLite, a
single file that one process writes at a time. Chapter 33
must prove that two members cannot both take the last
place, which needs a database that runs separate
connections at once and locks rows (select_for_update).
SQLite does neither. Readers' practice data, including
members' two-factor rows, must survive the move.
## Options
- A: PostgreSQL 18, installed natively on each computer,
reached through psycopg 3.
- B: PostgreSQL in Docker now (Docker arrives in
Chapter 62).
- C: a hosted PostgreSQL service on a free tier.
- D: stay on SQLite and simulate the race.
## Decision
A. PostgreSQL 18 (18.7 was the newest patch on 22 November
2026; 19.0 was three days old), installed natively, with
psycopg[binary] 3.3.9. Settings read DB_ENGINE, DB_NAME,
DB_USER, DB_PASSWORD, DB_HOST, and DB_PORT through
python-decouple; with DB_ENGINE empty Django uses SQLite,
so earlier checkpoints still run. The database and an
empty template for tests use the builtin C.UTF-8
collation, so text sorts by code point on every computer,
as it did on SQLite. Data moved once, with dumpdata in XML
(JSON keeps times only to the millisecond) and natural
foreign keys, leaving out rows that migrations make again
and sessions, then checked by compare_databases.py.
## Consequences
- Each reader installs and runs a database server, with
a role and password kept in .env, never in Git.
- Tests create test_otahque from otahque_template; the
role needs CREATEDB. The whole suite runs with
--parallel at checkpoints, one app within steps.
- contains lookups become case-sensitive; Chapter 56's
search uses icontains or full-text search.
- The dump and backup files hold password hashes, phone
numbers, and two-factor secrets: kept outside the
project and deleted after use.
- Chapter 33 can lock rows; Chapter 62 moves the server
into a container; Chapter 66 adds connection pooling.
## Revisit
At the Django 6.2 upgrade or in Chapter 62, whichever
comes first: PostgreSQL 19, once hosts and the official
image offer it. If many readers cannot install a server,
reconsider B.
Chapter 29’s design note warns that any copy of the database gives away every member’s two-factor codes. This chapter made two such copies, so the note says so. In docs/design/passwords-and-two-factor.md, under “Known risks”, the first item now reads:
docs/design/passwords-and-two-factor.md (in Known risks)
a backup, or an export gives every member's codes.
Chapter 32's move file and backup are such copies:
they stay outside the project and are deleted after
use. Exports leave the table out (Chapter 41); Chapter
In docs/design/erd.md, after the “Sources:” line, add:
docs/design/erd.md (after Sources)
Database: PostgreSQL 18 from Chapter 32 (ADR-005); SQLite
before it. Text sorts by code point (C.UTF-8).
Check and commit:
Terminal
uv run python manage.py makemigrations --check --dry-run
git add .
git status --short
git commit -m "Move to PostgreSQL"
Output
No changes detected
M .env.example
M .gitignore
M accounts/templates/accounts/profile.html
M check_environment.py
A compare_databases.py
M config/settings.py
A docs/adr/ADR-005-postgresql.md
M docs/design/erd.md
M docs/design/passwords-and-two-factor.md
M events/templates/events/edit.html
M events/templates/events/form.html
M events/tests.py
M pyproject.toml
M static/otahque/site.css
M static/otahque/source.css
M templates/allauth/elements/button.html
M templates/allauth/elements/form.html
M templates/allauth/layouts/base.html
M templates/base.html
M uv.lock
[master 8c4db1c] Move to PostgreSQL
20 files changed, 437 insertions(+), 47 deletions(-)
create mode 100644 compare_databases.py
create mode 100644 docs/adr/ADR-005-postgresql.md
The commit holds no database file and no dump: .env, db.sqlite3, and db-before-32.sqlite3 are ignored, and the dumps were written outside the project and deleted.
When something goes wrong
Every recovery in Table 32.4 keeps db-before-32.sqlite3 and your committed work. None of them drops the otahque database once Step 8 has loaded it.
Table 32.4 — Diagnosing the move
Symptom
Likely cause
Recovery
psql is not recognized
Programs not on PATH
Add the bin folder to Path; open a new terminal
Connection refused
Server stopped, or another port
Start the PostgreSQL service; check DB_PORT
Password authentication failed
Wrong .env value
\password otahque as administrator; update .env
'charmap' codec in Step 4
No -X utf8
Delete the partial file; dump again with -X utf8
Duplicate key on content types
Dumped without the exclusions
Drop and recreate otahque (Step 3), migrate, load the right dump
Comparison shows DIFF
Wrong options, or rows changed since the dump
Read which tables; dump and load again into a fresh otahque
Tests: permission denied
Role lacks CREATEDB
ALTER ROLE otahque CREATEDB;
Tests: template does not exist
Step 9's template missing
Create otahque_template with createdb
Tests: template is being accessed
A psql session open in it
Close that session, run again
Sort test fails
Template made without C.UTF-8
Drop otahque_template, create it as in Step 9
Back on SQLite by mistake
DB_ENGINE empty in .env
Check with check_environment.py; fix .env
Two rows mention dropping and recreating otahque. That is safe only before you have used the new database for real work, because until then the copy in db-before-32.sqlite3 holds everything. After that, a damaged otahque is restored from a backup like Step 10’s.
Optional lab: a table Otahque does not own
Many Django projects must read tables that another system creates and owns: a city’s venue list, a membership database, an old application. Django’s inspectdb command reads such a table and writes a model for it, and managed = False tells migrations to leave the table alone. This lab makes a small venue table owned by another role, lets Otahque read it, and shows that a write is refused by the database itself. It changes no file in the project.
As the administrator, connected to the otahque database (psql -h localhost -U postgres -d otahque on Windows), run:
psql, as the administrator, in otahque
CREATE ROLE venues_owner;
CREATE TABLE legacy_venue (
venue_id integer PRIMARY KEY,
name text NOT NULL,
city varchar(80),
seats smallint
);
ALTER TABLE legacy_venue OWNER TO venues_owner;
INSERT INTO legacy_venue VALUES
(1, 'Central Library hall', 'Leeds', 120),
(2, 'Riverside studio', 'Pune', 40),
(3, 'Online', NULL, NULL);
GRANT SELECT ON legacy_venue TO otahque;
The table belongs to venues_owner; otahque may only read it. Ask Django what it sees:
Terminal
uv run python manage.py inspectdb legacy_venue
Output
from django.db import models
class LegacyVenue(models.Model):
venue_id = models.IntegerField(primary_key=True)
name = models.TextField()
city = models.CharField(max_length=80, blank=True,
null=True)
seats = models.SmallIntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'legacy_venue'
Read the generated model as a draft: the field types follow the table, venue_id is the primary key, managed = False and db_table keep the table’s own name, and the lines of advice that inspectdb prints first (left out above) list what to check. Save this practice file as lab_venues.py, which uses the model as inspectdb wrote it, run it like the other practice files, and delete it:
lab_venues.py (practice file; delete it afterwards)
"""Read a table Otahque does not own, then try to change it."""
from django.db import DatabaseError, models, transaction
class LegacyVenue(models.Model):
"""A venue from the city's system, read through Django."""
venue_id = models.IntegerField(primary_key=True)
name = models.TextField()
city = models.CharField(max_length=80, blank=True,
null=True)
seats = models.SmallIntegerField(blank=True, null=True)
class Meta:
app_label = 'events'
managed = False
db_table = 'legacy_venue'
for venue in LegacyVenue.objects.order_by('name'):
print(venue.venue_id, venue.name, venue.city, venue.seats)
try:
with transaction.atomic():
LegacyVenue.objects.create(venue_id=9, name='New hall')
except DatabaseError as error:
print('write refused:', str(error).splitlines()[0])
Output
1 Central Library hall Leeds 120
3 Online None None
2 Riverside studio Pune 40
write refused: permission denied for table legacy_venue
The rows read, and the write is refused by PostgreSQL, not by Django: the permission belongs to the table’s owner. makemigrations --check --dry-run still prints No changes detected, because the model never entered models.py. Remove the lab as the administrator:
psql, as the administrator, in otahque
DROP TABLE legacy_venue;
DROP ROLE venues_owner;
Using several databases at once, with a router choosing between them, is a different topic; Chapter 67 takes it up.
Work through Table 32.5 from the folder that holds manage.py.
Table 32.5 — Verification checklist for Chapter 32
Check
Command or action
Expected result
Starting point
test --parallel on SQLite
Found 342 test(s); OK
Copy kept
git status --short after Step 1
No output; the copy is ignored
PostgreSQL programs
psql --version
psql (PostgreSQL) 18.x
Database sort order
psql ... -c "\l otahque"
builtin, C.UTF-8
Django on PostgreSQL
check_environment.py
Last line: postgresql 18.x
Data moved
compare_databases.py db-before-32.sqlite3
every table matches
Two-factor kept
Sign in as Sam
Asked for his code
New ids continue
Create an event
The next number after the highest
Test fails first
Sort test before the template
FAILED, Zebra talk expected first
Tests pass
test --parallel
Found 343 test(s); OK
No migration waiting
makemigrations --check --dry-run
No changes detected
Backup restores
Step 10
every table matches; copy dropped
Wide screen
New event at 1280 px
Two columns; button at its own width
Phone width
Device toolbar, 390 px
One column; no sideways page scroll
Committed
git status --short
No output
Not verified
macOS, Linux, WSL installs; PostgreSQL 18.7
Readers on those systems
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 31 checkpoint holding a reader’s data, with each listing applied in the order printed, against a PostgreSQL 18.3 server made for the check with password sign-in and the computer’s default sort order. The check typed ALTER ROLE where you type \password, because a script cannot answer a password prompt. In the printed outputs the project folder is shortened to ... and the port is shown as your 5432. The installers themselves were not run, and the pages were checked in Microsoft Edge at 390 and 1280 pixels.
Que. 3 Why does the dump leave out content types, permissions, and groups, but keep the admin’s history?
Flip to check your answerFold answer back
Answer. migrate makes content types, permissions, and Chapter 30’s groups again on the new database, with new ids, so loading the old ones would collide with them. The admin’s history was made by people, using the admin, and exists nowhere else, so it moves. Its link to a content type is written by name, which finds the new id.
Que. 4 The settings say TEST: {'TEMPLATE': 'otahque_template'}. Why not use otahque itself as the template?
Flip to check your answerFold answer back
Answer. A copy of otahque would bring every real row into the test database, so tests would no longer start empty, and PostgreSQL refuses to copy a database while anyone is connected to it, such as a running development server. otahque_template is empty and has only one job: carrying the right sort order into every test database.
Que. 5 After the move, compare_databases.py prints skip django_session. Is something wrong?
Flip to check your answerFold answer back
Answer. No. Sessions were left out on purpose: they are short-lived sign-ins, not records. The only effect is that everyone signs in once more on PostgreSQL.
Que. 6 A reader’s .env has the line DB_ENGINE= with nothing after it. Which database does Django use, and how can the reader tell?
Flip to check your answerFold answer back
Answer. SQLite, because the settings treat an empty value as missing. uv run python check_environment.py shows it on its last line, sqlite followed by a version, instead of postgresql 18.
Mini-Challenge
Que. 7 Table 32.2 says contains now respects case. Write two tests in events/tests.py that show it on PostgreSQL: searching titles for “python” finds “Python clinic” with icontains and finds nothing with contains. Run them on PostgreSQL. Then say what the second test would do on SQLite, and why that is a reason to search with icontains.
Flip to check your answerFold answer back
Answer. At the end of events/tests.py:
events/tests.py (add at the end)
class TitleSearchTests(TestCase):
"""A search for a word in titles, on PostgreSQL."""
@classmethod
def setUpTestData(cls):
save_event(title='Python clinic')
def test_icontains_ignores_case(self):
found = Event.objects.filter(title__icontains='python')
self.assertEqual(found.count(), 1)
def test_contains_keeps_case(self):
found = Event.objects.filter(title__contains='python')
self.assertEqual(found.count(), 0)
Terminal
uv run python manage.py test events -k TitleSearch
Output
Found 2 test(s).
Creating test database for alias 'default'...
...
Ran 2 tests in ...s
OK
On SQLite the second test fails: SQLite’s LIKE ignores case for the letters A to Z, so contains finds the title there too. The same query giving different answers on two databases is a reason to say what you mean, as Chapter 19 advised: icontains ignores case on both. Chapter 56 builds Otahque’s search. Remove both tests afterwards, or keep them as a record of the difference.
What We Learned
A database server runs on its own and serves many connections, signed in as roles; that is what makes row locks and Chapter 33 possible.
PostgreSQL 18 is pinned instead of the days-old 19, and psycopg 3’s binary package is pinned for development.
Settings read the database from .env; with no DB_ENGINE, earlier checkpoints still run on SQLite, and check_environment.py says which is in use.
Moving between engines: leave out what migrations make again, follow relations with natural foreign keys, keep each row’s own id, and write XML so times keep their microseconds.
loaddata resets the id sequences; rows inserted another way need sqlsequencereset.
A move is checked by comparing both databases, table by table, not by looking at pages.
Tests copy a template database; TEST['TEMPLATE'] gives them Otahque’s sort order, and the role needs CREATEDB.
A backup is proved by restoring it into a copy and comparing; the copy and every dump are removed afterwards, because they hold personal data.
inspectdb and managed = False read a table that another system owns, and the database role, not Django, refuses writes.
Key terms
Use Table 32.6 to explain this chapter’s ideas in your own words.
Table 32.6 — Key terms from Chapter 32
Term
Meaning
Database server
A program that owns the data and serves clients over connections.
Role
A database user with a password and rights, such as otahque.
Driver
The package through which Python talks to the server: psycopg.
Natural key
A value that names a row, such as an email address, instead of its id.
Sequence
PostgreSQL's counter for the next id of a table.
Collation
The rules a database uses to compare and sort text.
Code point
The number Unicode gives each character.
Template database
The database a new one is copied from.
Restore rehearsal
Restoring a backup into a copy and comparing it with the original.
Unmanaged model
A model with managed = False: migrations leave its table alone.
Readiness checkpoint: you are ready for Chapter 33 when check_environment.py ends with postgresql 18, compare_databases.py db-before-32.sqlite3 prints every table matches, Sam signs in with his two-factor code, all 343 tests pass with --parallel, makemigrations --check --dry-run prints No changes detected, a backup has been restored and compared and the copy removed, no dump file is left, and the commit is made.
Git Commit
Your Chapter 32 work was committed in Step 12, with the message “Move to PostgreSQL”. It holds the database settings read from .env with SQLite as the fallback and a template for test databases; psycopg in pyproject.toml and uv.lock; the six database names in .env.example; the .gitignore rule for the SQLite copy; check_environment.py naming the database; compare_databases.py; the sort-order test; the wider page, two-column forms, and the account panel, with the stylesheet rebuilt; ADR-005; and the notes on copies of two-factor data and on the database in the ERD. It holds no data: your .env, both SQLite files, and the dumps stay out of Git.
These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead and ask you to diagnose and to defend a decision. They are extension questions, not a gate to the next chapter. Practice files are run with uv run python manage.py shell -c "exec(open('NAME').read())" and deleted afterwards; the commands for L2 and L4 build and remove their own scratch database, and never touch otahque.
L1 (Junior): Why move from SQLite to PostgreSQL now, and not at deployment?
What the interviewer is testing: Can you tie a technical change to a need the product has today?
Flip to check your answerFold answer back
Perfect answer: Because the next feature cannot be proved without it. Chapter 33 must show that two members asking for the last place at the same moment get exactly one place between them. That needs separate connections running at once and a lock on the event row. SQLite has one writer at a time and no row locks, so the race can be neither shown nor fixed on it. Moving now also means every later chapter is developed and tested on the database production will use, so differences such as case-sensitive contains or sort order appear on a developer’s computer, not after deployment.
Table 32.7 — What each database can do for Otahque
Question
SQLite
PostgreSQL
Writers at once
One
Many
Lock one row
No
Yes
Production host offers it
Rarely
Almost always
Behind the scenes:
two databases (summary)
SQLite one file, one writer, no select_for_update
PostgreSQL a server, many connections, row locks
Chapter 33 needs the second
Code proof:l1_features.py asks Django what each backend supports:
l1_features.py (practice file; delete it afterwards)
"""Compare what SQLite and PostgreSQL can do for Otahque."""
from django.db import connection
from django.db.backends.sqlite3.base import DatabaseWrapper
SQLite = DatabaseWrapper.features_class
print('running on:', connection.vendor)
for name in ('has_select_for_update',
'has_select_for_update_skip_locked'):
print(f'{name}: SQLite {getattr(SQLite, name)},',
f'PostgreSQL {getattr(connection.features, name)}')
with connection.cursor() as cursor:
cursor.execute('SHOW max_connections')
print('connections at once:', cursor.fetchone()[0])
Output
running on: postgresql
has_select_for_update: SQLite False, PostgreSQL True
has_select_for_update_skip_locked: SQLite False, PostgreSQL
True
connections at once: 100
Common mistakes:
Moving “for performance” without a measurement; Otahque’s reason is a capability, not speed.
Waiting until deployment, and meeting the differences for the first time on a live server.
Follow-up the interviewer might ask:
Would you keep SQLite for the tests to make them faster? (No: tests must use the database whose behaviour they prove.)
What else does PostgreSQL give Otahque later? (Full-text search in 56, constraints and indexes in 55.)
L2 (Mid-Level): Predict what loaddata does if the dump includes content types
What the interviewer is testing: Do you know which rows migrations create, and why ids differ between databases?
Flip to check your answerFold answer back
Perfect answer: It fails with a duplicate key on django_content_type. migrate has already created a content type for every model on PostgreSQL, numbered in the order the migrations ran there. The dump holds SQLite’s content types, with SQLite’s numbers. loaddata saves each by its id: where the id is free it inserts a row, and that row has the same app and model name as one PostgreSQL already holds, so the unique rule on app and model refuses it. The fix is to leave content types, permissions, and groups out, and let --natural-foreign point at them by name.
Figure 32.4 — Why content types collide.
Behind the scenes:
content types (summary)
PostgreSQL (admin, logentry) has id 1, made by migrate
dump (admin, logentry) has SQLite's id
loaddata new row, same app and model -> refused
Code proof: the commands dump everything from SQLite and load it into a scratch database otahque_l2. In PowerShell:
psycopg.errors.UniqueViolation: duplicate key value violates
unique constraint
"django_content_type_app_label_model_76bd3d3b_uniq"
django.db.utils.IntegrityError: Problem installing fixture
'...\..\everything.xml':
Could not load contenttypes.ContentType(pk=1): duplicate
key value violates unique constraint
"django_content_type_app_label_model_76bd3d3b_uniq"
Deleting PostgreSQL’s content types before loading: it works once, and leaves permissions pointing at missing rows.
Leaving out content types without --natural-foreign: the admin’s history then points at the wrong models.
Follow-up the interviewer might ask:
Why is the error about (admin, logentry) in particular? (It is the first content type, the first row that collides.)
Would the same dump load into an empty database with no migrations? (No: there would be no tables to load into.)
L3 (Senior): Defend leaving out permissions and groups, but keeping the admin’s history
What the interviewer is testing: Can you separate data that code defines from data that people made, and prove the result?
Flip to check your answerFold answer back
Perfect answer: Permissions are defined by the models and created by Django after each migration; the Organizers and Administrators groups are defined by Chapter 30’s data migration. Both exist on the new database before anything is loaded, so copying them would duplicate them, and the copies would carry SQLite’s ids. What people did with them, such as Sam’s membership of Organizers, moves with the member, as group names. The admin’s history is different: each row records something a person did, and nothing can make it again, so it moves, with its content type written by name. The proof is the comparison script, which compares remade rows by name, every one of them, so a group with a missing permission would show.
Figure 32.5 — Remade rows and history.
Behind the scenes:
two kinds of rows (summary)
made by code content types, permissions, groups
made by people members, events, places, admin history
move the second kind, by natural keys
Code proof:l3_ids.py shows that the same permission has different ids on the two sides:
l3_ids.py (practice file; delete it afterwards)
"""Show that a permission's id differs between the databases."""
import sqlite3
from django.contrib.auth.models import Permission
old = sqlite3.connect('db-before-32.sqlite3')
for codename in ('add_event', 'view_registration'):
before = old.execute(
'SELECT id FROM auth_permission WHERE codename = ?',
[codename],
).fetchone()[0]
now = Permission.objects.get(codename=codename).pk
print(f'{codename}: SQLite id {before}, PostgreSQL id {now}')
Output
add_event: SQLite id 25, PostgreSQL id 34
view_registration: SQLite id 36, PostgreSQL id 46
Common mistakes:
Leaving out admin.logentry because “it is only a log”: it is Chapter 30’s record of who changed what in the admin.
Assuming a group someone edited in the admin moves: it does not; migrations define the groups, so an edit belongs in a migration.
Follow-up the interviewer might ask:
What if a reader had added a third group by hand? (It would be lost; the comparison would show auth_group differing, and the fix is to add it again, or by a migration.)
Why not keep sessions too? (They are short-lived and tied to the old setup; signing in again costs nothing.)
L4 (Staff): After a move, Soni’s profile address changed from 5 to 4. Diagnose it
What the interviewer is testing: Can you work from a symptom to an option, and prove the cause?
Flip to check your answerFold answer back
Perfect answer: Ids changed only for members, so look at what is special about members: they have a natural key, their email address. With --natural-primary, dumpdata leaves out the id of any row whose model has a natural key, and loaddata lets the new database number them. In the old database the twin account made and deleted in Chapter 21 left a gap at 4; on PostgreSQL the members were numbered without gaps, so Soni moved from 5 to 4. Everything pointing at members by key still works, because it was written by email, but every address, bookmark, and plain number that names a member, such as an audit row’s target, now means someone else. The fix is to dump with --natural-foreign only, which keeps every id. Looking ahead, it is also why the comparison script compares ids for ordinary rows.
Figure 32.6 — Following a changed id to its cause.
Behind the scenes:
ids (summary)
SQLite Sam 1, Sai 2, Raj 3, (deleted 4), Soni 5
--natural-primary -> Soni 4 on PostgreSQL
--natural-foreign -> Soni 5, as before
Code proof: the commands repeat the move with --natural-primary into a scratch database otahque_l4 and compare it with the SQLite copy:
Copying a recipe’s options without asking what each does; --natural-primary is common in recipes.
Checking only the row counts, which match: the difference is in the ids.
Follow-up the interviewer might ask:
When is --natural-primary the right choice? (For fixtures loaded into databases that already hold other rows, where fixed ids would collide.)
How would you find every place an old member id is stored as a plain number? (Search the models for integer fields holding ids, such as AuditEvent.target_id.)
L5 (Lead): Defend a native PostgreSQL 18 now, and Docker in Chapter 62
What the interviewer is testing: Can you weigh a choice for a whole group of people, with its costs and the moment to revisit it?
Flip to check your answerFold answer back
Perfect answer: The readers are beginners on Windows, macOS, and Linux. A native install adds one program, managed the way their system manages programs, and they meet the database as a service they start, sign in to, and back up, which is exactly what Chapter 62 later puts in a container. Docker now would add a second new tool to a chapter that is already about a new tool, a chapter early. A hosted database would make every test depend on the network and an account. On the version: PostgreSQL 19 was three days old, hosts and the official image lag a new major version, and Django names nothing above its minimum of 15; version 18 is supported until 2030 and runs the whole suite. The decision is recorded in ADR-005 with two triggers to revisit it: Chapter 62 or the Django 6.2 upgrade, whichever comes first, and many readers unable to install a server.
Figure 32.7 — Choosing how readers get a database.
Behind the scenes:
the choice (summary)
now native PostgreSQL 18, three platforms
62 Docker image, same data, restore rehearsal
revisit 62 or Django 6.2: PostgreSQL 19
Code proof:l5_versions.py prints the versions in use and Django’s minimum:
l5_versions.py (practice file; delete it afterwards)
"""Print the versions in use here, and Django's minimum."""
import psycopg
from django.db import connection
floor = connection.features.minimum_database_version
server = connection.pg_version
print('PostgreSQL server:', server // 10000, server % 10000)
print('Django needs at least:', floor[0])
print('psycopg:', psycopg.__version__,
'| libpq:', psycopg.pq.version() // 10000)
Choosing the newest version because it is newest, without asking who must run it.
Recording the choice without the trigger that should reopen it.
Follow-up the interviewer might ask:
What would make you choose Docker now? (Readers failing to install, or a need for several services at once, such as Redis.)
How would you upgrade from 18 to 19 later? (A restore rehearsal into the new version first, as in Step 10, then the switch.)
Next: Chapter 33, Transactions, concurrency, and the last available seat, where two members ask for Sam’s last place at the same moment, and PostgreSQL’s row lock decides.