ContentsClose contents
Pre-release
Chapter 18 · Migrations: creating and changing the databaseCHAPTER 18

Complete six-part pre-release for review. The event and user tables follow the proposed models from Chapters 16 and 17; the slug lab is a disposable experiment, not part of Otahque's design.

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 EIGHTEEN

Migrations: creating and changing the database

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

Prerequisites: Chapters 8, 15, 16, and 17, including the Chapter 17 project, its 25 passing tests, its committed accounts.User model, its empty db.sqlite3, and the practice helper setup_django.py from Chapter 16

What you’ll build: Otahque’s first migrations and tables, four tests that use a real database, and a local superuser, followed by a disposable lab copy in which you change a table that already holds rows, forwards and backwards.

Why This Matters

Sam wants to put the November meetup into Otahque for real. Until now, every event the pages showed came from a list in the code, and the Event model from Chapter 16 described a table that did not exist. Sai’s account is in the same position: Chapter 17 wrote the user model and tested that it hashes passwords, but nothing could be saved, because the database was still empty. If Otahque restarted, nothing would be lost, because nothing had been kept. That changes in this chapter. Otahque gets its tables, and the first accounts it saves survive a restart.

Creating tables once is the easy part. The harder part comes months later, when the team needs to change a table that already holds registrations. Imagine someone adding a required column to the event table by typing a command into the live database. The command fails on the rows that already exist, or quietly fills them with a value nobody chose. Another teammate’s copy of the database no longer matches the code, and nobody can say which changes have been made where. Django’s answer is the migration: a small, versioned file that describes one change to the database’s structure, travels with the code in Git, and is applied in the same order on every computer that runs Otahque.

This chapter turns the models from Chapters 16 and 17 into tables, through migrations you generate, read, and preview before you apply them. Your tests start using a real database. You create the first account, an administrator account for your own computer. Then, in a disposable copy of the project, you change a table that already holds events, run the change forwards and backwards, and see that no row is lost.

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

  • explain what a migration is, and why Django separates writing one (makemigrations) from applying it (migrate);
  • read a generated migration file and preview its SQL and the order Django will apply it in;
  • apply migrations and confirm what Django has recorded as applied;
  • write tests that save to a database, and say where that database comes from;
  • create a local superuser with createsuperuser;
  • change a table that holds rows in reviewable, reversible steps, including a data migration that uses historical models.

This chapter creates the tables the Chapter 15 ERD describes for events and members, and changes nothing else in the reader project. It does not teach queries: the few lines that save and read rows are previews of Chapter 19. Relationships between tables, such as registrations, arrive in Chapter 20, and database constraints, including the decision about email letter case, in Chapter 21. The superuser is not used to sign in anywhere yet; Django’s admin site is Chapter 23. PostgreSQL is Chapter 32, and conflicts between teammates’ migrations, squashing, and production rollouts are Chapter 64.

PAGE 001

What You Need to Know

From models to tables

A model describes a table, and Chapter 16 showed that importing one creates nothing. Something has to turn the description into a real table, and later turn each change to the description into a change to the table.

New Concept: a migration

What problem exists? The database’s structure, its schema, has to match the models on every computer that runs Otahque: yours, a teammate’s, the test database, and one day the server. Each change has to be made once, in order, and never forgotten.

What did people do before? They kept SQL scripts with numbered names, ran them by hand, and wrote down somewhere which ones each database had received. When the note was wrong, databases drifted apart.

What is a migration? A Python file, kept in an app’s migrations folder, that describes one step in the schema’s history, such as “create the Event table” or “add a column”. makemigrations compares the models with the existing migration files and writes a new file for the difference. migrate applies the files a database has not yet received, and records each one in that database.

Why use migrations? They are reviewable like any code, committed with the model change they belong to, applied in a known order, and can often be reversed. A migration is to the schema what a commit from Chapter 8 is to the code: a named step in a shared history.

Now let’s use it. Otahque’s first two migrations create the event and user tables.

The two commands are separate on purpose. Writing a migration is a change to the code: you read it, test it, and commit it. Applying it is a change to one database: yours now, the test database in a moment, a server later. Keeping them apart means the same reviewed file is what every database receives. Figure 18.1 shows the route a model change takes.

Five numbered cards from left to right. An orange card for models.py, the code we write, leads to a purple card for makemigrations, which compares models with migration files. Its arrow leads to an orange card for the migration files in each app’s migrations folder, marked as committed to Git. A purple card for migrate reads those files and writes to a green database zone, which holds the app tables, such as events_event and accounts_user, and the django_migrations table listing what this database has applied. A grey note under the files says every database, the test database included, receives the same files.
Figure 18.1 — From a model change to a database table, through a reviewed migration.

Inside a migration file

Django writes migration files for you, but you read every one before committing it, as you would a teammate’s code.

New Concept: the parts of a migration file

What problem exists? A file you cannot read is a file you cannot review. You need to know what a migration will do before it runs.

What did people do before? A hand-written SQL script said exactly what it did, but not what it needed first or how to undo it.

What is in the file? One class, Migration, with a few attributes. initial = True marks an app’s first migration. dependencies lists the migrations that must already be applied, as pairs of app label and migration name. operations lists the changes, in order: CreateModel makes a table, AddField adds a column, AlterField changes one, and RunPython runs Python code that changes data. A model with a custom manager marked use_in_migrations, like Chapter 17’s UserManager, also lists it under managers.

Why read it? The file is what every database will receive. Reading it shows whether Django understood your change, and whether it depends on what you expect.

Now let’s use it. Step 3 reads Otahque’s two first migrations.

Dependencies decide the order. Each app’s migrations form a chain, 0001, 0002, and so on, in which each one depends on the one before. Migrations can also depend on another app’s migrations. Otahque’s user model has many-to-many links to Django’s auth permissions and groups, so its first migration depends on the latest auth migration. In the other direction, Django’s own admin app records which user made each change, so its first migration depends on whichever app AUTH_USER_MODEL names. Chapter 17’s L5 code proof showed that dependency as ('accounts', '__first__'). Django puts every migration of every installed app into one migration graph and applies them in an order that satisfies every dependency. That is why accounts.User had to be created in the first migration of the accounts app: Django’s own apps wait for it.

How Django knows what changed, and what has run

Under the Hood: the autodetector and the django_migrations table

To decide what to write, makemigrations never looks at the database’s tables or columns. It loads every migration file and replays their operations, in dependency order, into an in-memory description of each model, called the project state. It then compares that state with the models in your code. The part of Django that does the comparison is the autodetector. Each difference becomes an operation: a model in the code but not in the state becomes CreateModel, a new field becomes AddField, a changed option becomes AlterField. If nothing differs, it reports “No changes detected”. migrate, on the other hand, depends on the database, and on one table in particular, django_migrations, which it creates on its first run. Each row records one applied migration by app and name, with the time it was applied. migrate applies, in graph order, every migration that has no row, and adds a row after each. So the files say what the schema should be, and the table says how far this database has come. A file without a row is waiting to be applied; this is why deleting a database’s rows, or its files, causes confusion that is hard to undo. makemigrations reads the same table for one purpose only: to check that the applied history is consistent with the files, which matters in Step 2.

Because each database keeps its own record, your db.sqlite3, a teammate’s, and the test database can be at different points in the same history, and migrate brings each one forward from where it is.

Schema migrations and data migrations

Most migrations change structure. Some must also change the rows inside a table, because the new structure needs values the old rows do not have.

New Concept: data migrations and historical models

What problem exists? Adding a column to a table with rows leaves every existing row without a value. If the column must hold something meaningful, such as a value worked out from each row’s title, no single default will do.

What did people do before? They ran a one-off script against each database after changing the table, and hoped every copy received it.

What is a data migration? A migration whose operation, RunPython, calls a function you write. The function receives apps, a registry of historical models: versions of each model as they stood at that point in the migration history, built from the migration files. You get one with apps.get_model('events', 'Event'). A second function, the reverse code, undoes the change when the migration is unapplied. RunPython.noop, a function that does nothing, stands in when there is nothing to undo.

Why historical models? A migration may run months after it was written, when the real model has changed again. Importing events.models.Event would give the model as it is today, with fields that may not exist yet at that point in the history. A historical model matches the table at exactly that point. It has the fields, and managers marked use_in_migrations, but none of your own methods.

Now let’s use it. The lab in Step 7 fills a new column with a data migration, and reverses it.

Table 18.1 compares the two kinds.

Table 18.1 — Schema and data migrations compared
Question Schema migration Data migration
Changes Tables and columns Rows inside tables
Written by makemigrations, from the models You, in an empty migration
Typical operations CreateModel, AddField, AlterField RunPython
Uses the models No Historical models from apps.get_model()
Reversed by Django, for most operations The reverse code you write

On SQLite and PostgreSQL, Django runs each migration inside a transaction: either every operation in that migration takes effect, or none does. If a run of several migrations fails, the ones already applied stay applied, the one that failed is rolled back, and the rest are not attempted, so the run stops between two migrations, never in the middle of one. On MySQL, schema changes cannot be rolled back this way. Otahque uses SQLite until Chapter 32 moves it to PostgreSQL. Step 7 shows both a rollback and a run that stops part-way.

Try it yourself

Que. 1 Raj suggests that makemigrations should look at db.sqlite3 to see which columns already exist. Why does it compare with the migration files instead?

Flip to check your answerFold answer back

Answer. The migration files are the shared history every database receives, and they are in Git; each database is only one copy, at some point in that history. If makemigrations read your database, a column you had added by hand, or a migration you had not yet applied, would change what it wrote, and the file would not suit anyone else’s database. Comparing the code with the replayed files gives the same answer on every computer.

Tests that use a database

Every test so far has been a SimpleTestCase, which refuses to touch a database. Saving a user needs one.

New Concept: TestCase and the test database

What problem exists? A test that saves rows must not touch your development database, and each test must start from the same empty tables, whatever the test before it saved.

What did people do before? Tests ran against a shared database and cleaned up after themselves, until one forgot and the next test failed for no visible reason.

What is TestCase? A test class whose tests may use the database. When a run includes one, Django first creates a separate test database and builds it by applying every migration, then runs each TestCase test inside a transaction that it rolls back afterwards, and destroys the test database at the end. With SQLite, the test database lives in memory, so db.sqlite3 is never touched.

Why use it? The test database is built from the same migrations as yours, so the tests also prove that the migrations work from an empty database. Each test sees empty tables.

Now let’s use it. Step 2 writes four TestCase tests, before the migrations exist.

Use SimpleTestCase whenever a test does not need the database: it is faster, and it fails loudly if a database query sneaks in. Use TestCase when the behaviour is about saved rows, as it is for a user who must be stored and read back.

Prefer committing db.sqlite3?

Committing the database file can seem simpler than committing migrations: a teammate would receive the tables and the rows at once. It works for a day. Then two people’s copies diverge, Git cannot merge a binary file, and private data, such as account emails and password hashes, ends up in the repository’s history for good. Chapter 8’s .gitignore already keeps db.sqlite3 out. Migrations are the shared part: small text files that each computer applies to its own database. Sample data, when Otahque needs it, comes from tools chosen in Chapter 41, not from a copied file.

Changing a table that already holds rows

Adding a column to an empty table is one migration. Adding a required, unique column to a table that already holds rows takes three, because each row needs its own value before the database can insist on one.

In practice: changing a populated table in steps

Situation. A team wants each event to have a readable address part, a slug, such as python-meetup-3, and wants the database to guarantee that no two events share one. The table already holds events.

Application. Django’s documentation describes a three-step pattern. First, add the column allowing empty values, so the existing rows are valid. Second, a data migration gives each row its own value. Third, change the column to require a value and to be unique, which now succeeds because every row has a distinct one. Each step is a separate migration, reviewed and reversible.

Consideration. Between the second and third steps, a row saved by code that does not yet set a slug would break the third step. On a small project with one database, the steps run back to back. On a live site, the order of code and migration deployments has to be planned, which is Chapter 64’s subject.

Otahque’s ERD has no slug, and Chapter 10’s addresses use each event’s id, so the lab in Step 7 adds one only in a disposable copy, to practise the pattern. The reader project is not changed.

PAGE 002

How We Build It

Start from Chapter 17, in the folder containing manage.py, with your own .env, the locked environment, 25 passing tests, the user model committed, and a db.sqlite3 with no tables. You change one file, accounts/tests.py, and create one, config/tests.py, both before any migration exists. makemigrations then writes a first migration, 0001_initial.py, in the migrations folder of each app. migrate creates the tables in db.sqlite3, and createsuperuser saves the first account. A practice script goes in ../practice. At the end of Step 6, 29 tests pass, every migration is applied, and the work is committed. Step 7 then copies the committed project into ../practice/migrations-lab, a lab you discard afterwards, and changes the event table there.

The Custom Way

This illustration keeps a schema up to date by hand, with numbered SQL scripts and a home-made table of applied versions; do not add it to the project:

import sqlite3

SCRIPTS = {
    1: 'CREATE TABLE event (id INTEGER PRIMARY KEY,'
       ' title TEXT NOT NULL)',
    2: 'ALTER TABLE event ADD COLUMN slug TEXT',
}

db = sqlite3.connect(':memory:')
db.execute('CREATE TABLE schema_version (number INTEGER)')


def upgrade():
    done = {n for (n,) in db.execute(
        'SELECT number FROM schema_version')}
    for number in sorted(SCRIPTS):
        if number not in done:
            db.execute(SCRIPTS[number])
            db.execute('INSERT INTO schema_version'
                       ' VALUES (?)', (number,))


upgrade()
upgrade()
print(db.execute('SELECT number FROM schema_version')
      .fetchall())
[(1,), (2,)]

It works: running upgrade() twice applies each script once. Now list what it does not do. It has one sequence of numbers for the whole project, so two apps, or two teammates, cannot add scripts without colliding, and nothing says that one script needs another app’s table first. The scripts are written by hand, so nothing checks that they match the models, and a forgotten column only appears when a page fails. There is no way back: undoing script 2 means writing another script. Tests would need their own copy of the whole routine. And Django’s own apps, which need the user table to exist before their tables can point at it, would have no way to say so. Django’s migrations do each of these things, and the steps below use them.

The Django Way

Seven steps follow. Steps 1 to 6 work in the reader project; Step 7 works in a lab copy. The tests come before the migrations, so you see them fail first.

Step 1: Check the starting point

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

uv run python manage.py test

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

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

OK

Then confirm that the database has no tables, with the query from Chapters 15 to 17. In PowerShell, beside manage.py:

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

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

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

Expected result: nothing at all. Now ask Django what migrations your models need, without writing anything. --dry-run reports what would be written and writes nothing, and --check makes the command finish with an error status when something is missing:

uv run python manage.py makemigrations --check --dry-run
Migrations for 'events':
  events\migrations\0001_initial.py
    + Create model Event
Migrations for 'accounts':
  accounts\migrations\0001_initial.py
    + Create model User

On Windows, in PowerShell and in Git Bash, Django prints paths with backslashes; on macOS and Linux they have forward slashes. + Create model names the operation each file would hold. Both apps need a first migration. No file has been written: each app’s migrations folder still holds only __init__.py. Finally, git status --short should print nothing.

If the table query lists tables, migrate ran at some point since Chapter 15. Rename db.sqlite3, for example to db-before-ch18.sqlite3, keep it, and carry on: Django creates a new, empty file the next time it needs one. If a 0001_initial.py file already exists in either app, from an earlier attempt, do not delete it; move it into ../practice and keep it to compare with the one you generate in Step 3.

Step 2: Write the database tests first

Chapter 17’s tests stopped before anything was saved. These tests save users and read them back. Open accounts/tests.py and change its imports to these:

from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.test import SimpleTestCase, TestCase

from .models import User

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

class UserCreationTests(TestCase):
    """Members saved through the manager, in the database."""

    def test_create_user_saves_a_member(self):
        user = User.objects.create_user(
            email='Sai@EXAMPLE.org',
            password='correct horse',
            display_name='Sai',
        )
        saved = User.objects.get(pk=user.pk)
        self.assertEqual(saved.email, 'Sai@example.org')
        self.assertTrue(
            saved.check_password('correct horse')
        )
        self.assertTrue(saved.is_active)
        self.assertFalse(saved.is_staff)
        self.assertFalse(saved.is_superuser)

    def test_create_superuser_saves_both_flags(self):
        user = User.objects.create_superuser(
            email='sam@example.org',
            password='correct horse',
            display_name='Sam',
        )
        saved = User.objects.get(pk=user.pk)
        self.assertTrue(saved.is_staff)
        self.assertTrue(saved.is_superuser)

    def test_email_is_unique_in_the_database(self):
        User.objects.create_user(
            email='raj@example.org',
            password='correct horse',
            display_name='Raj',
        )
        with self.assertRaises(IntegrityError):
            User.objects.create_user(
                email='raj@example.org',
                password='another horse',
                display_name='Raj K.',
            )

User.objects.get(pk=user.pk) fetches the saved row again by its primary key. It is a one-line preview of Chapter 19’s queries, used here so that each test checks what the database holds, not only the object in memory. The first test completes Chapter 17’s manager contract: create_user() saves the email with its domain lowercased and its local part as typed, which says nothing yet about whether Sai@ and sai@ are one member; Chapter 21 decides that. The second checks that create_superuser() saves both flags. The third saves two accounts with the same email and expects the database itself to refuse the second with an IntegrityError, the error Django raises when a database rule is broken. unique=True was only a description in Chapter 17; once the table exists, it is a rule the database enforces.

The second new file guards every app at once. A model change committed without its migration is one of the most common mistakes in Django projects: the code expects a column that no database has. Create config/tests.py:

"""Tests that cover the whole project."""
from io import StringIO

from django.core.management import call_command
from django.test import TestCase


class MigrationTests(TestCase):
    """Every model change has a migration."""

    def test_every_model_change_has_a_migration(self):
        output = StringIO()
        try:
            call_command(
                'makemigrations', '--check', '--dry-run',
                stdout=output,
            )
        except SystemExit:
            self.fail(
                'Missing migrations:\n' + output.getvalue()
            )

call_command() runs a management command from Python, as if you had typed it. StringIO collects what it prints, so the failure message can show it. When something is missing, --check ends the command with SystemExit, which the test turns into a failure naming the missing migrations. It lives in config, the project package, because the rule covers every app. It must be a TestCase, not a SimpleTestCase, because makemigrations reads the database’s applied migrations to check that they are consistent.

Common Error: a database test written as SimpleTestCase

If either new class inherits from SimpleTestCase, its tests fail with DatabaseOperationForbidden, and the message says that database queries are not allowed in a SimpleTestCase. The guard test fails the same way, because makemigrations queries the applied migrations. Change the base class to TestCase, as in the listings.

Run every test:

uv run python manage.py test

Expected result, shortened with ...:

Found 29 test(s).
Creating test database for alias 'default'...
Traceback (most recent call last):
...
ValueError: Dependency on app with no migrations: accounts

This red stage looks different from earlier ones. Django finds 29 tests, then stops while building the test database, before any test runs, with the same error migrate gave in Chapter 17. The test database is built from migrations, and there are none. The manager tests describe behaviour that needs tables; the guard test is different, because it cannot fail first in the usual way. It is a guard against future mistakes, and Step 7 makes it fail on purpose.

Step 3: Generate and read the migrations

Write the migrations, beside manage.py, in any of the three shells. With no app label, makemigrations writes what every installed app needs:

uv run python manage.py makemigrations
Migrations for 'events':
  events\migrations\0001_initial.py
    + Create model Event
Migrations for 'accounts':
  accounts\migrations\0001_initial.py
    + Create model User

Open events/migrations/0001_initial.py. Django wrote it in its own layout, with some lines over 150 characters wide, and its first line records the Django version and the moment you ran the command, so your file carries a different date. Keep it exactly as Django wrote it: generated files are not reformatted or edited by hand. This excerpt wraps the long lines and marks left-out parts with ...:

# Generated by Django 6.1.2 on ...

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Event',
            fields=[
                ('id', models.BigAutoField(
                    auto_created=True, ...)),
                ('title', models.CharField(max_length=200)),
                ('starts_at', models.DateTimeField()),
                ('ends_at', models.DateTimeField()),
                ...
                ('status', models.CharField(
                    choices=[('draft', 'Draft'), ...],
                    default='draft', max_length=20)),
            ],
            options={
                'ordering': ['starts_at'],
            },
        ),
    ]

initial = True marks the app’s first migration. The event table needs nothing else first, so dependencies is empty. CreateModel repeats every field from Chapter 16’s model, including the id Django adds, and the ordering option. The migration keeps its own copy of the fields, so it still means the same thing after the model changes later. Now open accounts/migrations/0001_initial.py:

# Generated by Django 6.1.2 on ...

import accounts.managers
import django.utils.timezone
from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('auth', '0012_alter_user_first_name_max_length'),
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ...
                ('email', models.EmailField(
                    max_length=254, unique=True, ...)),
                ('display_name', models.CharField(
                    max_length=100)),
                ...
                ('groups', models.ManyToManyField(
                    ..., to='auth.group', ...)),
                ('user_permissions', models.ManyToManyField(
                    ..., to='auth.permission', ...)),
            ],
            ...
            managers=[
                ('objects', accounts.managers.UserManager()),
            ],
        ),
    ]

This is the migration Chapter 17 prepared for. User is created in accounts’ first migration, as the swapped user model must be. It depends on auth’s latest migration because groups and user_permissions link to auth’s group and permission tables. The managers list records UserManager, because Chapter 17 marked it use_in_migrations, so a data migration that creates users could call create_user() on the historical model.

Common Error: No changes detected

If makemigrations prints No changes detected here, either the migration files already exist, from an earlier run, or an app is missing from INSTALLED_APPS. Check both folders for 0001_initial.py, and compare INSTALLED_APPS with Chapter 17’s listing. Never rename a generated migration, or edit its dependencies, to make it fit: other migrations refer to it by name.

Step 4: Preview before applying

Two commands show what migrate would do, without changing the database. sqlmigrate prints the SQL one migration would run on this database. Run it for the events app:

uv run python manage.py sqlmigrate events 0001

Expected result, with the long line shortened:

BEGIN;
--
-- Create model Event
--
CREATE TABLE "events_event" ("id" integer NOT NULL ...
COMMIT;

BEGIN; and COMMIT; are the transaction from What You Need to Know: the whole migration takes effect, or none of it does. On your screen, the CREATE TABLE line continues with one column for each field. Near its end, the capacity column carries CHECK ("capacity" >= 0): the database rule behind PositiveIntegerField, which Chapter 16 predicted. The app label is events, plural; sqlmigrate event 0001 stops with CommandError: No installed app with label 'event'.

Run the same command for accounts 0001. It prints three CREATE TABLE statements: accounts_user, with "email" varchar(254) NOT NULL UNIQUE, and two link tables, accounts_user_groups and accounts_user_user_permissions, which hold the many-to-many links, followed by CREATE INDEX statements that make those links fast to look up.

migrate --plan lists every migration migrate would apply, in order, with its operations:

uv run python manage.py migrate --plan

Expected result, shortened with ...:

Planned operations:
contenttypes.0001_initial
    Create model ContentType
...
auth.0001_initial
    Create model Permission
    Create model Group
    Create model User
...
auth.0012_alter_user_first_name_max_length
    Alter field first_name on user
accounts.0001_initial
    Create model User
admin.0001_initial
    Create model LogEntry
...
events.0001_initial
    Create model Event
sessions.0001_initial
    Create model Session

Two details deserve a look. accounts.0001_initial comes after auth.0012 and before admin.0001, exactly as the dependencies require. And auth.0001_initial still lists Create model User. That is Django’s built-in user, whose operation stays in auth’s history; because AUTH_USER_MODEL names accounts.User, the built-in model is swapped out, and Django skips creating its table.

Step 5: Apply the migrations

Apply every migration, beside manage.py, in any of the three shells:

uv run python manage.py migrate

Expected result, shortened with ...:

Operations to perform:
  Apply all migrations: accounts, admin, auth, ...
Running migrations:
  Applying contenttypes.0001_initial... OK
...
  Applying accounts.0001_initial... OK
...
  Applying events.0001_initial... OK
  Applying sessions.0001_initial... OK

With Django 6.1.2, migrate printed 20 Applying lines: Django’s own apps and Otahque’s two. The count is what this version printed, not something to check; what matters is that accounts.0001_initial and events.0001_initial both end in OK. Ask Django what it has recorded:

uv run python manage.py showmigrations accounts events
accounts
 [X] 0001_initial
events
 [X] 0001_initial

[X] means that django_migrations has a row for that migration in this database; [ ] would mean the file exists but has not been applied. Run showmigrations with no app label to see every app; no line should show [ ].

Now list the tables. The Step 1 query would also list Django’s indexes, so this one asks only for tables. In PowerShell, beside manage.py:

uv run python -m sqlite3 db.sqlite3 `
    "SELECT name FROM sqlite_schema WHERE type='table'"

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

uv run python -m sqlite3 db.sqlite3 \
    "SELECT name FROM sqlite_schema WHERE type='table'"
('django_migrations',)
('sqlite_sequence',)
('django_content_type',)
('auth_group_permissions',)
('auth_permission',)
('auth_group',)
('accounts_user',)
('accounts_user_groups',)
('accounts_user_user_permissions',)
('django_admin_log',)
('events_event',)
('django_session',)

SQLite lists tables in the order they were created, so the list follows the migration order: django_migrations first, because migrate creates it before anything else, then the tables of contenttypes, auth, accounts, admin, events, and sessions.

Table 18.2 explains what each group of tables is for.

Table 18.2 — The tables after the first migrate
Tables Created by Holds
accounts_user, accounts_user_groups, accounts_user_user_permissions accounts.0001 Otahque's accounts and their links to groups and permissions
events_event events.0001 Otahque's events
auth_group, auth_group_permissions, auth_permission auth Django's groups and permissions (Chapter 30)
django_admin_log admin The admin site's change history (Chapter 23)
django_content_type contenttypes One row per model, used by permissions
django_session sessions Signed-in sessions (Chapter 27)
django_migrations migrate One row per applied migration
sqlite_sequence SQLite SQLite's own record of the last id used in each table

There is no auth_user table: the built-in user is swapped out, as planned. Run every test again:

uv run python manage.py test

Expected result, shortened with ...:

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

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

The red stage is now green. Creating test database and Destroying test database mark the test database’s life: Django built it from the migrations you just wrote, ran the tests in it, and threw it away. The run takes several seconds, mostly spent hashing passwords with 1,500,000 PBKDF2 iterations for each saved user; Chapter 34 decides whether tests should use a faster hasher.

Common Error: a migration that fails

If migrate stops with an error, read the last line of the message and fix its cause; do not delete db.sqlite3 or any migration file. On SQLite, the failed migration was rolled back and the ones before it stay recorded, so running migrate again after the fix is safe: it skips what is applied and retries the rest. That advice holds for SQLite and PostgreSQL. On a database without transactional schema changes, check the failed migration and the database state before retrying; Chapter 64 covers recovery on a live system.

Step 6: Create a superuser and commit

A superuser is an account with is_staff and is_superuser set: Django treats it as holding every permission, and its admin site, in Chapter 23, lets it change everything. Create one for your own computer. The command asks for the fields USERNAME_FIELD and REQUIRED_FIELDS name, then a password twice; the password is not shown as you type. Use the fictional address below and a password of your own that you have not used anywhere else. Never write it in a file. Beside manage.py, in PowerShell, Git Bash, a macOS shell, or Linux/WSL Bash:

uv run python manage.py createsuperuser
Email address: sam@example.org
Display name: Sam
Password:
Password (again):
Superuser created successfully.

The prompts come from Chapter 17’s model: Email address from USERNAME_FIELD and the field’s name, Display name from REQUIRED_FIELDS. The command then calls the manager’s create_superuser(), so the email is normalized and the password hashed as Step 2’s tests require.

The command also checks your answers before saving. Each refusal asks again, so you can carry on in the same run:

  • Error: That email address is already taken. The account exists already, perhaps from an earlier attempt; keep it, and press Ctrl+C to stop, or enter a different address.
  • Error: This field cannot be blank. The display name was left empty.
  • Error: Your passwords didn't match. Type the same password twice.
  • This password is too common., followed by Bypass password validation and create user anyway? [y/N]:. Answer N, then choose a stronger password. These checks are the password validators listed in config/settings.py, which Chapter 29 reviews.

Common Error: Superuser creation skipped

createsuperuser needs a terminal to read the password from. If its input is not a terminal, it prints Superuser creation skipped due to not running in a TTY. and creates nothing. In this book’s checks, Git for Windows 2.51 gave the command a terminal in Git Bash; an older Git Bash window may not. If you see the message there, run the same command in PowerShell, or start it with winpty, a helper that ships with Git for Windows: winpty uv run python manage.py createsuperuser.

For scripts, such as an automated check, the command also has a form that asks nothing: --noinput reads the email, display name, and password from environment variables named DJANGO_SUPERUSER_EMAIL, DJANGO_SUPERUSER_DISPLAY_NAME, and DJANGO_SUPERUSER_PASSWORD. This book’s verification uses that form; you do not need it.

Now create a short practice script that checks what was saved, without printing the hash:

import setup_django  # loads Otahque's settings first
from django.contrib.auth import get_user_model

User = get_user_model()
sam = User.objects.get(email='sam@example.org')
print(sam.email, sam.display_name)
print(sam.is_active, sam.is_staff, sam.is_superuser)
print(sam.password.split('$')[0])

Run it from the folder that holds manage.py, in any of the three shells:

uv run python ../practice/check_superuser.py
sam@example.org Sam
True True True
pbkdf2_sha256

The account is active, staff, and a superuser, and its password is stored as a PBKDF2 hash. It lives only in your db.sqlite3, which Git ignores. Now look at what Git sees:

git status --short
 M accounts/tests.py
?? accounts/migrations/0001_initial.py
?? config/tests.py
?? events/migrations/0001_initial.py

The two migrations and the two test files, and nothing else: no db.sqlite3, no superuser. If db.sqlite3 appears, .gitignore has lost Chapter 8’s line; put it back rather than committing the database. Commit now, before the lab, so that Step 7 can copy a committed project. Commit each model change together with its migration, as here, so that every commit holds code and schema that match:

git add accounts config events
git commit -m "Add the first migrations and database tests"

git status --short then prints nothing. Chapter 17’s Common Error asked you to move any early 0001_initial.py files into ../practice; if you did, compare them with the new files now, excluding the first line, and then you may keep or discard the old copies, which Git never saw.

Step 7: Change a table with rows, in a lab copy

This step is an experiment. Otahque’s design does not include a slug, so you make the change in a copy of the project and discard the copy afterwards. Run every command in this step inside the lab folder, never in your project.

From the folder that holds manage.py, clone the committed project into the practice folder. The same command works in PowerShell, a macOS shell, and Linux/WSL Bash:

git clone . ../practice/migrations-lab
Cloning into '../practice/migrations-lab'...
done.

git clone . copies the repository in the current folder, with the commit you just made. It does not copy what Git ignores, so the lab has no .env, .venv, or db.sqlite3. Copy your .env into the lab. In PowerShell:

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

In a macOS shell or Linux/WSL Bash:

cp .env ../practice/migrations-lab/.env

Then move into the lab, build its environment from the lock file, and create its tables, in any of the three shells:

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

uv sync --locked creates the lab’s own .venv with the same locked packages, and migrate applies the same 20 migrations to the lab’s new db.sqlite3. The lab is a separate project with a separate database: nothing here can reach your real db.sqlite3. Its Git remote points at your project, and Git refuses by default to push into a folder with the branch checked out; never push from the lab anyway.

A table change matters only when the table has rows. Create a helper that adds three events. It goes in the practice folder, beside setup_django.py. Like Event.objects.create() itself, which saves a new row in one call, it is a preview of Chapter 19:

"""Add three sample events to the lab's database.

Run from the lab folder: uv run python ../add_lab_events.py
"""
from datetime import UTC, datetime

import setup_django  # loads the lab's settings first
from events.models import Event

for title, day in [('Python meetup', 12),
                   ('Django sprint', 19),
                   ('Python meetup', 26)]:
    Event.objects.create(
        title=title,
        starts_at=datetime(2026, 11, day, 18, tzinfo=UTC),
        ends_at=datetime(2026, 11, day, 20, tzinfo=UTC),
        timezone='Europe/London',
        location='Virtual',
        capacity=40,
    )
print(Event.objects.count(), 'events')

From the lab folder, the practice folder is one level up, so run it with ../:

uv run python ../add_lab_events.py
3 events

Two events share a title on purpose: their slugs must still differ. Figure 18.2 shows the three migrations you are about to write.

A timeline of three numbered orange migration cards from left to right, after a green card for the event table holding 3 rows. Card 1, 0002_event_slug, adds a slug column that allows NULL. Card 2, 0003_fill_slugs, runs Python that gives each row its own slug, such as python-meetup-3. Card 3, 0004_alter_event_slug, makes the slug required and unique. A blue arrow above the cards points forwards, labelled migrate events. A grey arrow below points backwards, labelled migrate events 0001, noting that clear_slugs() empties the column first. A green strip along the bottom says 3 rows at every step.
Figure 18.2 — Adding a required, unique column to a table that holds rows, in three reversible migrations.

Migration 0002: add the column, allowing empty values. In the lab’s events/models.py, add one line after title:

    slug = models.SlugField(max_length=200, null=True)

A SlugField holds letters, numbers, hyphens, and underscores, the characters that read well in an address. null=True lets the existing rows have no value yet. Before writing the migration, run the guard test from Step 2 on its own; test config runs the tests in the config package:

uv run python manage.py test config

Expected result, shortened with ...:

Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
...
AssertionError: Missing migrations:
Migrations for 'events':
  events\migrations\0002_event_slug.py
    + Add field slug to event
...
FAILED (failures=1)

This is the mistake the guard exists for: a model change with no migration. The message says which migration is missing. Now write it:

uv run python manage.py makemigrations
Migrations for 'events':
  events\migrations\0002_event_slug.py
    + Add field slug to event

Apart from its first line, the new file is short enough to show in full, with its one long line wrapped:

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('events', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='slug',
            field=models.SlugField(
                max_length=200, null=True),
        ),
    ]

It depends on the app’s previous migration, and its one operation adds the column.

Migration 0003: give each row its own value. Ask Django for an empty migration in the events app, with a name you choose. In PowerShell:

uv run python manage.py makemigrations events --empty `
    --name fill_slugs

In a macOS shell or Linux/WSL Bash:

uv run python manage.py makemigrations events --empty \
    --name fill_slugs
Migrations for 'events':
  events\migrations\0003_fill_slugs.py

The file has a dependencies list naming 0002_event_slug and an empty operations list. This is the one migration you write yourself, so replace its whole contents, header line included, with this:

from django.db import migrations
from django.utils.text import slugify


def fill_slugs(apps, schema_editor):
    """Give every event a slug from its title and number."""
    Event = apps.get_model('events', 'Event')
    for event in Event.objects.all():
        event.slug = f'{slugify(event.title)}-{event.pk}'
        event.save(update_fields=['slug'])


def clear_slugs(apps, schema_editor):
    """Undo fill_slugs(): empty every slug."""
    Event = apps.get_model('events', 'Event')
    Event.objects.update(slug=None)


class Migration(migrations.Migration):

    dependencies = [
        ('events', '0002_event_slug'),
    ]

    operations = [
        migrations.RunPython(fill_slugs, clear_slugs),
    ]

RunPython takes the forward function and the reverse function. Both receive apps, the historical models, and schema_editor, which these functions do not need. apps.get_model('events', 'Event') returns the Event model as it stands after 0002: with a nullable slug, and without the model’s own __str__(). slugify(), from Django’s text utilities, turns Python meetup into python-meetup, and adding the id makes each value distinct, even for the two meetups. save(update_fields=['slug']) writes only that column. Event.objects.update(slug=None) changes every row in one statement; the reverse code puts the rows back as 0002 left them. As before, the queries are previews of Chapter 19.

Common Error: importing the model in a migration

Writing from events.models import Event in a migration works on the day you write it, because the model and the table match. Later, when the model gains a field that a later migration adds, the import gives the newest model, and this older migration fails on a column that does not exist yet at its point in the history. Always use apps.get_model() inside RunPython.

Migration 0004: require a value and make it unique. Replace the slug line in the lab’s events/models.py, removing null=True and adding unique=True in one edit:

    slug = models.SlugField(max_length=200, unique=True)

Run makemigrations. Django notices that a column which allowed empty values will no longer allow them, and asks what to do about rows that might hold one. Type 2 and press Enter:

uv run python manage.py makemigrations

Expected result, with long lines shortened:

It is impossible to change a nullable field 'slug' on ...
Please select a fix:
 1) Provide a one-off default now (will be set on all ...
 2) Ignore for now. Existing rows that contain NULL ...
 3) Quit and manually define a default value in models.py.
Select an option: 2
Migrations for 'events':
  events\migrations\0004_alter_event_slug.py
    ~ Alter field slug on event

Option 2 tells Django that the existing rows are handled elsewhere, “with a RunPython or RunSQL operation”, as the full line says, and that is true: 0003 gives every row a slug before 0004 runs. Option 1 would ask for one value to put into every row still empty, which is the wrong tool for a unique column: one shared value is exactly what unique=True forbids. ~ marks an operation that changes something: the new file holds one AlterField, which makes the column required and unique.

Common Error: adding a unique, required field in one step

Skipping 0002 and 0003, and adding the final, unique field line straight away, makes makemigrations ask for a one-off default. Whatever you give it, every existing row receives the same value, and migrate stops with an IntegrityError that reports a failed UNIQUE constraint on the slug column. The failed migration is rolled back: showmigrations shows it unapplied, and the three rows are untouched. Fix it by removing that migration file, which no database has applied, and following the three steps. This was observed in a second, separate lab copy; you need not try it.

Run it forwards. Apply the three migrations to the lab’s database:

uv run python manage.py migrate events
Operations to perform:
  Apply all migrations: events
Running migrations:
  Applying events.0002_event_slug... OK
  Applying events.0003_fill_slugs... OK
  Applying events.0004_alter_event_slug... OK

Look at the slugs. In PowerShell, from the lab folder:

uv run python -m sqlite3 db.sqlite3 `
    "SELECT id, title, slug FROM events_event"

In a macOS shell or Linux/WSL Bash:

uv run python -m sqlite3 db.sqlite3 \
    "SELECT id, title, slug FROM events_event"
(1, 'Python meetup', 'python-meetup-1')
(2, 'Django sprint', 'django-sprint-2')
(3, 'Python meetup', 'python-meetup-3')

Each row has its own slug, and the two meetups differ by their ids.

Run it backwards. Naming an app and a migration makes migrate move that app to exactly that point, unapplying everything after it, newest first:

uv run python manage.py migrate events 0001
Operations to perform:
  Target specific migration: 0001_initial, from events
Running migrations:
  Rendering model states... DONE
  Unapplying events.0004_alter_event_slug... OK
  Unapplying events.0003_fill_slugs... OK
  Unapplying events.0002_event_slug... OK

0004 is undone first, making the column optional again; then clear_slugs() empties it; then the column is removed. Check the record:

uv run python manage.py showmigrations events
events
 [X] 0001_initial
 [ ] 0002_event_slug
 [ ] 0003_fill_slugs
 [ ] 0004_alter_event_slug

The files are still there; only their rows in django_migrations are gone. Now check the table’s columns and its rows. pragma_table_info() is SQLite’s way of listing a table’s columns. In PowerShell:

uv run python -m sqlite3 db.sqlite3 `
    "SELECT name FROM pragma_table_info('events_event')"
uv run python -m sqlite3 db.sqlite3 `
    "SELECT COUNT(*) FROM events_event"

In a macOS shell or Linux/WSL Bash:

uv run python -m sqlite3 db.sqlite3 \
    "SELECT name FROM pragma_table_info('events_event')"
uv run python -m sqlite3 db.sqlite3 \
    "SELECT COUNT(*) FROM events_event"
('id',)
('title',)
('starts_at',)
('ends_at',)
('timezone',)
('location',)
('capacity',)
('status',)
(3,)

The slug column is gone, and all three events remain. The slug values themselves are gone too: reversing a migration that removes a column removes its data, which is why reverse code deserves as much care as forward code. Run uv run python manage.py migrate events again, and the three migrations reapply, recomputing the same slugs.

Optional: a migration with no way back. To see why the reverse function matters, change the operation in 0003_fill_slugs.py to migrations.RunPython(fill_slugs), leaving out clear_slugs, and run uv run python manage.py migrate events 0001. Django unapplies 0004, then stops at 0003 with a traceback whose last line is an IrreversibleError, saying that this migration’s operation is not reversible. Run showmigrations events: 0002 and 0003 are still applied, and 0004 is not. The run stopped between two migrations, exactly as the transaction rule says. Put clear_slugs back, then run migrate events to return to the latest state. When a data migration truly has nothing to undo, pass migrations.RunPython.noop as the reverse function, so that it can still be unapplied.

When you have finished, you can delete the lab, the migrations-lab folder inside the practice folder; your project never saw any of it. If you ran a lab command in your project by mistake, git status --short in the project shows exactly which files changed. Check that each one is a lab change, such as events/models.py or a new 0002_event_slug.py, before restoring it with git restore events/models.py or seeing which new files would be removed with git clean -n. Then remove only those. Your committed work is safe either way.

When something goes wrong

Table 18.3 — Migration problems and safe recovery
Symptom Likely cause Safe recovery
The Step 1 query lists tables migrate ran in an earlier chapter Rename db.sqlite3 and keep it as a backup
ValueError: Dependency on app with no migrations: accounts Tests or migrate run before Step 3 Run makemigrations; nothing to undo
DatabaseOperationForbidden A database test inherits SimpleTestCase Change the base class to TestCase
No changes detected (Step 3) Files already exist, or an app is not installed Check both migrations folders and INSTALLED_APPS
CommandError: No installed app with label 'event' App label misspelled Use events, plural
A migrate run fails part-way A migration's operation failed Fix the cause and rerun migrate; keep the database and the files
That email address is already taken The superuser exists already Keep it; press Ctrl+C or use another address
Superuser creation skipped ... not running in a TTY Input is not a terminal Use PowerShell, or winpty in Git Bash
db.sqlite3 appears in git status .gitignore line removed Restore the Chapter 8 line; never commit the database
Guard test fails: Missing migrations A model changed without a migration Run makemigrations, read the file, commit both together
IntegrityError: UNIQUE constraint failed A unique field added in one step Remove the unapplied file; use the three steps
IrreversibleError: ... is not reversible RunPython has no reverse code Add a reverse function, or RunPython.noop
Lab command run in the project Wrong folder git status, then git restore only the lab's files
PAGE 003

Verify Your Work

Work through Table 18.4 from the folder that holds manage.py, unless a row names the lab. The test rows come first, because they are the evidence that the migrations build a working database from nothing.

Table 18.4 — Verification checklist for Chapter 18
Check Command or action Expected result
Red stage seen The Step 2 run, before migrations Found 29 test(s), then ValueError
Tests pass uv run python manage.py test Found 29 test(s), OK
Nothing missing uv run python manage.py makemigrations --check --dry-run No changes detected
Both apps applied uv run python manage.py showmigrations accounts events [X] 0001_initial for both
Nothing waiting uv run python manage.py showmigrations No line shows [ ]
Tables created The Step 5 table query accounts_user and events_event; no auth_user
Superuser saved uv run python ../practice/check_superuser.py sam@example.org Sam; True True True; pbkdf2_sha256
Committed git status --short No output
Files tracked git ls-files Both 0001_initial.py files; no db.sqlite3
Lab reversed The Step 7 backward run No slug column; (3,)
Not verified macOS, Linux, WSL; PostgreSQL Readers on those systems; Chapter 32

makemigrations --check --dry-run prints No changes detected and finishes without an error status, which is exactly what the guard test asserts. The number of migrations migrate applied is not on the list: it belongs to the Django version, not to Otahque. The last row records what this chapter has not shown: its commands were checked in Windows PowerShell 5.1 and Git Bash, and the PostgreSQL behaviour waits for Chapter 32.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 2 Why does Django need two commands, makemigrations and migrate, rather than one that updates the database directly?

Flip to check your answerFold answer back

Answer. They change different things. makemigrations writes a file in the code, which you read, test, and commit with the model change. migrate changes one database, applying the files it has not received. Keeping them apart means every database, yours, a teammate’s, the test database, and a server, receives the same reviewed files in the same order.

Que. 3 showmigrations events shows [X] 0001_initial and [ ] 0002_event_slug. What does each mark mean, and what will migrate do?

Flip to check your answerFold answer back

Answer. [X] means this database’s django_migrations table has a row for 0001_initial, so it was applied. [ ] means the file 0002_event_slug.py exists but has not been applied here. migrate will apply 0002 and record it.

Que. 4 Inside RunPython, why does fill_slugs() call apps.get_model('events', 'Event') instead of importing Event from events.models?

Flip to check your answerFold answer back

Answer. apps.get_model() returns the historical model, matching the table at that point in the migration history. The imported model is the current one, which may have fields that a later migration adds; when the migration runs on a fresh database months later, those columns do not exist yet, and it fails.

Que. 5 In the lab, going back to 0001 unapplied 0002_event_slug. What happened to the slug values, and what happened to the three events?

Flip to check your answerFold answer back

Answer. Unapplying 0002 removed the slug column, and the values went with it; the reverse code had already cleared them. The three events, and every other column, remained. Reversing a migration that removes a column always removes that column’s data, so reverse code needs as much thought as forward code.

Que. 6 The 29 tests pass. Which test fails if a teammate later adds a field to Event and commits without running makemigrations?

Flip to check your answerFold answer back

Answer. test_every_model_change_has_a_migration in config/tests.py. It runs makemigrations --check --dry-run, which finds the missing migration and ends with SystemExit; the test fails with a message naming the missing migration file and its operation.

Mini-Challenge

Que. 7 In the lab copy only, imagine the team wants to split location into venue and city, both text. Without running anything, write in your notes the migrations you would need, in order, and the forward and reverse functions of the data migration. Assume each current location reads like Community hall, Leeds, and the reverse should join the two parts with a comma and a space.

Flip to check your answerFold answer back

Answer. Three migrations, as in Step 7. First, makemigrations writes a schema migration that adds venue and city, each CharField(max_length=200, blank=True), so the existing rows are valid with empty text. Second, a data migration from makemigrations events --empty --name split_location holding RunPython(split_location, join_location). split_location() gets Event with apps.get_model('events', 'Event'), and for each event uses event.location.partition(', ') to set venue to the part before the comma and city to the part after, saving with update_fields=['venue', 'city']. A location without a comma keeps all its text in venue and an empty city. join_location() does the opposite: it sets location to venue and city joined by ', ', or to venue alone when city is empty, and saves location. Third, once the code reads the new fields, a schema migration removing location. Its reverse would bring the column back empty, so the reverse of the data migration must run after it, which the dependency order guarantees: unapplying goes newest first. Whether the split is a good idea for Otahque is a product question; the ERD keeps one location.

What We Learned

  • A migration is a versioned file describing one step in the schema’s history. makemigrations writes it by comparing the models with the existing files; migrate applies it to one database and records it.
  • A migration file holds dependencies and operations; dependencies across apps put every migration into one graph, which is why the custom user had to be in accounts’ first migration.
  • The autodetector replays migration files, not the database; the django_migrations table records what each database has applied.
  • sqlmigrate and migrate --plan preview a migration’s SQL and order; showmigrations shows what is applied.
  • TestCase tests use a test database built from the migrations and discarded afterwards; SimpleTestCase tests cannot use a database.
  • createsuperuser asks for the fields the user model names, and saves the account through the manager.
  • Migrations are committed with their model change; db.sqlite3 never is.
  • A required, unique field on a table with rows takes three migrations: add it nullable, fill it with a data migration, then require it. Data migrations use historical models from apps.get_model() and need reverse code.
  • On SQLite and PostgreSQL, each migration is a transaction, so a failed run stops between migrations, never inside one.

Key terms

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

Table 18.5 — Key terms from Chapter 18
Term Meaning
Schema The structure of a database: its tables, columns, and rules.
Migration A versioned file describing one change to the schema or its data.
makemigrations Writes migration files for the differences between models and existing migrations.
migrate Applies unapplied migrations to a database and records them.
Dependency A migration that must be applied before another.
Migration graph Every installed app's migrations, ordered by their dependencies.
Autodetector The part of makemigrations that compares models with the replayed migrations.
django_migrations The table recording which migrations a database has applied.
Data migration A migration that changes rows, usually with RunPython.
Historical model A model rebuilt from migrations as it stood at one point in history.
Reverse code The function that undoes a RunPython operation when it is unapplied.
Transaction A group of database changes that take effect together or not at all.
TestCase A test class that may use the test database; each test is rolled back.
Superuser An account with is_staff and is_superuser set.

Readiness checkpoint: you are ready for Chapter 19 when all 29 tests pass, makemigrations --check --dry-run reports no changes, showmigrations shows every migration applied, the Step 5 table query lists Otahque’s two tables, the superuser check prints the output shown in Step 6, and git status --short prints nothing. Explain, in a sentence, why the test database contains Otahque’s tables although you never ran migrate on it. Return to the relevant step if any result is missing.

Git Commit

Your Chapter 18 work was committed at the end of Step 6, before the lab, so that the lab could copy it. For the record, these were the commands, in PowerShell, a macOS shell, or Linux/WSL Bash, beside manage.py:

git add accounts config events
git status --short
A  accounts/migrations/0001_initial.py
M  accounts/tests.py
A  config/tests.py
A  events/migrations/0001_initial.py
git commit -m "Add the first migrations and database tests"

Run git status --short in the project now: it prints nothing, because the lab’s changes live only in the lab’s own repository. Nothing from the lab is committed to your project.

PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, one at each of five levels from junior to lead. L1 and L2 check what you have just done. L3 asks why data migrations work the way they do. L4 and L5 look ahead to a live application with a team: attempt them now, and return to them after Chapter 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 setup_django.py. Run the L1 to L3 proofs from the folder that holds manage.py with uv run python ../practice/ followed by the file name, and the L4 and L5 proofs from the lab folder, as each one says.

L1 (Junior): What do makemigrations and migrate each do, and why are they separate?

What the interviewer is testing: Do you know the difference between describing a schema change and applying it?

Flip to check your answerFold answer back

Perfect answer: makemigrations compares the models with the migrations already written, and writes a new migration file in each app for the difference: operations such as CreateModel or AddField. It does not change the database, and it does not read its tables to decide what to write. migrate applies the migration files a database has not received, in dependency order, and records each one in that database’s django_migrations table. They are separate because the migration is code: it is reviewed, tested, and committed with the model change, and the same file is then applied to every database: a developer’s, the test database, and production. A command that changed the database straight from the models would leave nothing to review and no shared history.

Table 18.6 — makemigrations and migrate compared
Question makemigrations migrate
Reads Models and migration files Migration files and django_migrations
Writes New migration files Tables, columns, and rows
Touches the database No Yes
Committed to Git Its output, yes Nothing to commit
Runs When a model changes On every database

Behind the scenes:

models + files -> makemigrations -> new 0002_... file
review, test, commit the file with the model change
file + django_migrations -> migrate -> table changed
each database records its own applied migrations

Code proof: the migration files Django found for Otahque’s apps, and the ones this database has applied:

import setup_django
from django.db import connection
from django.db.migrations.loader import MigrationLoader

loader = MigrationLoader(connection)


def ours(keys):
    return sorted(f'{app}.{name}' for app, name in keys
                  if app in ('accounts', 'events'))


print('files:', *ours(loader.disk_migrations))
print('applied:', *ours(loader.applied_migrations))
files: accounts.0001_initial events.0001_initial
applied: accounts.0001_initial events.0001_initial

MigrationLoader is the part of Django both commands use to read the files and the applied records. After Step 5, the two sets are the same.

Common mistakes:

  • Running migrate after a model change and expecting it to notice, without makemigrations.
  • Committing the model change but not its migration file.
  • Thinking makemigrations reads the database’s columns.

Follow-up the interviewer might ask:

  • “What would showmigrations print if a teammate’s migration had been pulled but not applied?”
  • “How would you catch a missing migration before code is merged?”

L2 (Mid-Level): What is inside a migration file, and how does Django decide the order to apply migrations?

What the interviewer is testing: Can you read a migration and explain dependencies across apps?

Flip to check your answerFold answer back
Five numbered steps. Each migration lists its dependencies and operations. Every app’s migrations join one graph. Swappable dependencies point at the user model’s app. migrate applies them in an order that satisfies every dependency. django_migrations records each one as it is applied.
Figure 18.3 — How Django orders migrations across apps.

Perfect answer: A migration file defines a Migration class. initial marks an app’s first migration. dependencies lists the migrations that must already be applied, as app label and name pairs. operations lists the changes in order, such as CreateModel, AddField, AlterField, or RunPython, and a CreateModel may record options and managers. Within an app, each migration depends on the previous one, forming a chain. Across apps, a migration depends on whatever it needs: Otahque’s user migration depends on auth’s latest migration for the group and permission tables, and Django’s admin app depends on the user model’s app through swappable_dependency(settings.AUTH_USER_MODEL), which resolves to that app’s first migration. The loader combines every app’s migrations into one graph, and migrate applies them in an order that satisfies all the dependencies; migrate --plan shows that order.

Behind the scenes:

dependencies -> edges between migrations
graph        -> every installed app, one graph
swappable    -> ('accounts', '__first__') for the user
plan         -> an order that respects every edge

Code proof: the admin app’s dependencies, and the last two steps of the plan that leads to it:

import setup_django
from django.db import connection
from django.db.migrations.loader import MigrationLoader

loader = MigrationLoader(connection)
admin = loader.get_migration('admin', '0001_initial')
print(admin.dependencies)
plan = loader.graph.forwards_plan(('admin', '0001_initial'))
print(plan[-2:])
[('accounts', '__first__'), ('contenttypes', '__first__')]
[('accounts', '0001_initial'), ('admin', '0001_initial')]

admin.0001_initial depends on the first migration of whichever app holds the user model, so accounts.0001_initial comes immediately before it.

Common mistakes:

  • Renaming a migration file, which breaks every migration that depends on it by name.
  • Editing dependencies by hand to make an error go away.
  • Assuming migrations run in alphabetical or date order.

Follow-up the interviewer might ask:

  • “What would happen if the user model were created in accounts’ second migration?”
  • “How would you see the SQL one migration will run?”

L3 (Senior): Why must a data migration use apps.get_model() instead of importing the model?

What the interviewer is testing: Do you understand historical models, and why a migration must keep working long after it was written?

Flip to check your answerFold answer back
Five numbered steps. A migration may run months after it was written. Importing the model gives today’s fields and methods. apps.get_model() rebuilds the model from earlier migrations. It matches the table at that exact point. Custom methods are absent, so the code relies on fields only.
Figure 18.4 — Historical models keep a data migration valid over time.

Perfect answer: A migration runs whenever a database reaches it in the history: today on my database, next year on a new developer’s empty database, or in the test database on every run. If the migration imports events.models.Event, it gets the model as it is when it runs, which may include fields that later migrations add. On a fresh database those columns do not exist yet at that point, so the queries fail. RunPython passes the function an apps registry instead, and its get_model() returns a historical model, rebuilt by replaying the migrations up to that point. Its fields match the table exactly. It does not have the model’s own methods, such as __str__(), or custom managers unless they set use_in_migrations = True, so data migration code should depend only on fields. The same applies to the reverse function, which should restore the state before the migration, or be RunPython.noop when there is nothing to undo.

Behind the scenes:

import events.models.Event -> today's model, any time
apps.get_model(...)        -> model at this migration
has                        -> fields, migration managers
lacks                      -> your methods, e.g. __str__

Code proof: the historical Event at 0001_initial, compared with the current class:

import setup_django
from django.db import connection
from django.db.migrations.loader import MigrationLoader

from events.models import Event

loader = MigrationLoader(connection)
state = loader.project_state(('events', '0001_initial'))
Old = state.apps.get_model('events', 'Event')
print(Old is Event)
print(str(Event(title='Python meetup')))
print(str(Old(title='Python meetup')))
print(hasattr(Event, 'Status'), hasattr(Old, 'Status'))
False
Python meetup
Event object (None)
True False

The historical model is a different class. It prints Django’s generic text because it lacks Chapter 16’s __str__(), and it has no Status choices class; it has only what the migration files record.

Common mistakes:

  • Importing the current model inside RunPython.
  • Calling a custom model method inside a data migration.
  • Writing no reverse function, so the migration cannot be unapplied.

Follow-up the interviewer might ask:

  • “How would a data migration create users with the custom manager?”
  • “When is RunPython.noop the right reverse function, and when is it hiding a problem?”

L4 (Staff): You must add a required, unique field to a table with a million rows in production. How do you plan it?

What the interviewer is testing: Looking ahead: can you turn a one-line model change into a safe sequence of reviewable, reversible steps?

Flip to check your answerFold answer back
Five numbered steps. Add the column allowing NULL. Make new code write a value for every new row. Fill existing rows in batches with a data migration. Then require the value and add the unique rule. Rehearse forwards and backwards on a copy of production.
Figure 18.5 — Planning a required, unique field on a large, live table.

Perfect answer: I would not add it in one migration: every existing row would need a value at once, and a one-off default would give them all the same one, which the unique rule forbids. I would use the three-step pattern from Django’s documentation, planned around deployments. First, a migration adds the column allowing NULL, which most databases can do quickly. Second, a code release writes a value for every new or changed row, so the gap stops growing. Third, a data migration fills the existing rows; for a million rows I would process them in batches, and consider making that migration non-atomic or running the backfill as a separate command, because one long transaction can hold locks and run out of time. Fourth, once every row has a distinct value, a migration requires it and adds the unique rule. Each step has reverse code and is rehearsed forwards and backwards on a copy of production data, with timings, before the real run. This chapter showed the pattern on three rows; Chapter 64 adds the deployment and database details.

Behind the scenes:

0002 AddField null=True      -> quick, rows stay valid
release                      -> new rows get values
0003 RunPython, in batches   -> old rows get values
0004 AlterField unique=True  -> only when every row is set

Code proof: run from the lab folder, the three lab migrations, their operations, and whether each can be reversed:

import setup_django
from django.db import connection
from django.db.migrations.loader import MigrationLoader

loader = MigrationLoader(connection)
for name in ('0002_event_slug', '0003_fill_slugs',
             '0004_alter_event_slug'):
    migration = loader.get_migration('events', name)
    for operation in migration.operations:
        print(name, '|', operation.describe(), '|',
              operation.reversible)
0002_event_slug | Add field slug to event | True
0003_fill_slugs | Raw Python operation | True
0004_alter_event_slug | Alter field slug on event | True

Run it in the lab, where the practice folder is one level up. Every step can be reversed; 0003 only because it has clear_slugs. Without it, the middle line ends in False.

Common mistakes:

  • Adding unique=True and a required value in one migration on a populated table.
  • Filling a large table in one transaction without measuring it first.
  • Deploying the final migration before the code that writes the new field.

Follow-up the interviewer might ask:

  • “How would you know the backfill has finished before the last step?”
  • “What would you do if the unique step failed in production?”

L5 (Lead): Two developers each created 0005 in the same app, and a teammate wants to edit an applied migration. What rules would you set?

What the interviewer is testing: Looking ahead: can you set working rules that keep a shared migration history trustworthy?

Flip to check your answerFold answer back
Five numbered steps. Commit each model change with its migration. Never edit or delete a migration applied anywhere else. Catch two 0005 files before merging. Resolve conflicts with a new migration, not by editing. Keep demo data and database files out of migrations and Git.
Figure 18.6 — Working rules for a shared migration history.

Perfect answer: Two 0005 files that both depend on 0004 give the app two latest migrations, two leaf nodes, and Django refuses to continue until they are joined. Joining them with a merge migration, from makemigrations --merge, is Chapter 64’s subject. Editing an applied migration is a different problem: databases that already ran it will never run the new version, so their schemas silently diverge. Django’s documentation says migrations should rarely be edited by hand. My working rules for Otahque, which are team rules, not Django’s: commit each model change with its migration, in the same commit; never edit or delete a migration once it has been applied anywhere but your own computer, and make a new one instead; run the migration guard test and makemigrations --check in CI, which Chapter 34 sets up, so missing migrations and two leaf nodes are caught before merging; resolve conflicts with a merge migration, then rerun the tests; never put demo data in a migration, because migrations run in every environment, production included; and never “fix” a problem by deleting a shared database or its migration files.

Behind the scenes:

model + migration -> one commit
applied elsewhere -> never edit; add a new migration
two 0005 leaves   -> caught by --check; merge, Chapter 64
demo data, db     -> never in migrations or Git

Code proof: in the lab folder, two migrations with the same parent make Django stop. In PowerShell:

uv run python manage.py makemigrations events --empty `
    --name sam_note
cd events/migrations
Copy-Item 0005_sam_note.py 0005_raj_note.py
cd ../..
uv run python manage.py makemigrations --check --dry-run

In a macOS shell or Linux/WSL Bash:

uv run python manage.py makemigrations events --empty \
    --name sam_note
cd events/migrations
cp 0005_sam_note.py 0005_raj_note.py
cd ../..
uv run python manage.py makemigrations --check --dry-run

The last command prints, shortened:

CommandError: Conflicting migrations detected; multiple ...
To fix them run 'python manage.py makemigrations --merge'

The full first line names both leaves. Afterwards, delete the two 0005 files, with rm or Remove-Item, and the check prints No changes detected again.

Common mistakes:

  • Editing an applied migration and expecting others to receive it.
  • Renumbering one of two conflicting files by hand.
  • Seeding sample data in a migration, so it reaches production.

Follow-up the interviewer might ask:

  • “When would you allow a migration to be edited?”
  • “How would you review a merge migration?”

Next: Chapter 19 uses the new tables, saving, finding, filtering, and updating events with Django’s ORM.

PAGE 006