Django 6.1.3

9.5 Connections, transactions, and migrations

How migrations build a historical ProjectState

Why doesn’t migrate inspect your live database schema, and how does Django reconstruct historical model classes from migration files alone?

Ask a developer who has never read django/db/migrations/ how "manage.py makemigrations" or "manage.py migrate" works, and the standard guess is that Django inspects the live SQL tables, compares the columns against "models.py", and runs "ALTER TABLE" for the difference.

Django does not do that — and for three deep reasons. First, a SQL database schema cannot express Python-level concepts like "choices", custom "default" callables, "Meta.ordering", "through" model names, or proxy models. Second, live table inspection can never tell a column rename ("headline -> title") apart from dropping "headline" (destroying all data!) and adding an empty "title" column. Third, a migration created two years ago must replay deterministically on a brand-new staging database today, even if "models.py" has been refactored ten times since.

Instead, Django keeps the entire history in Python files, links them into a MigrationGraph, replays every operation in memory onto a ProjectState, and dynamically synthesizes frozen historical model classes inside a private StateApps registry.

MigrationLoader, MigrationGraph, and dependency DFS

When "migrate" or "makemigrations" starts, MigrationLoader reads two independent sources:

  1. On disk (MigrationLoader.load_disk): Scans every app in "INSTALLED_APPS" for a "migrations" package, imports each non-underscore Python module, extracts its Migration class, and stores (app_label, migration_name) -> Migration in "disk_migrations".
  2. In the database (MigrationRecorder.applied_migrations, MigrationRecorder.applied_migrations): Queries the "django_migrations" table — the only table MigrationLoader inspects in the database — to learn which (app, name) pairs are already applied.

MigrationLoader.build_graph then feeds every migration into a MigrationGraph: each migration becomes a Node, and each entry in "dependencies" (including symbolic keys like "('newsroom', '__first__')" or swappable_dependency(settings.AUTH_USER_MODEL)) and "run_before" becomes a directed edge. Notice the crucial comment in MigrationGraph’s docstring: migration numbering (0001_, 0002_) carries zero ordering authority — only explicit graph edges control execution order! That is how Django catches two git branches that both added a 0002_*.py migration depending on 0001_initial: MigrationGraph.leaf_nodes sees two leaf nodes for one app and refuses to run until you merge them.

To plan a migration run up to a target node (or backwards to an earlier node), MigrationGraph.forwards_plan and MigrationGraph.backwards_plan run MigrationGraph.iterative_dfs — a deterministic post-order depth-first search sorting parent keys so every dependency executes strictly before its dependents.

ProjectState, ModelState, and synthetic "__fake__" models

Once the graph defines an exact replay order, MigrationExecutor._create_project_state starts from an empty ProjectState (models = {}) and walks the plan calling Migration.mutate_state with "preserve=False" — which calls each operation’s "state_forwards(app_label, state)" method without touching the database at all!

Inside ProjectState, every model is stored as a lightweight ModelState (not to be confused with runtime instance state ModelState) holding pure Python metadata: "app_label", "name", "fields" (unattached Field clones, Field, using string references for relations), "options", "bases", and "managers".

Whenever an operation — such as RunPython or BaseDatabaseSchemaEditor — needs real Django model classes with Options and managers, accessing the cached property ProjectState.apps constructs a StateApps, a private subclass of Apps. StateApps.render_multiple loops over every ModelState, calling ModelState.render, which builds a fresh Meta class, clones every field, attaches "__module__": "__fake__", restores only managers that set "use_in_migrations = True" (shimming all other default managers with plain Manager, Manager!), and executes type(self.name, bases, body) — running ModelBase.__new__ inside that isolated StateApps registry!

Watch MigrationLoader, MigrationGraph.forwards_plan, and live vs. historical "Story" models execute on "desk/":

Recorded on Django 6.1.3 ch09-database script
5. MigrationGraph, MigrationLoader, and ProjectState historical models
  loader: disk_migrations=20 applied_migrations=20 leaf_apps=['admin', 'auth', 'contenttypes', 'newsroom', 'sessions', 'subscribers']
  forwards_plan_subscribers = [('contenttypes', '0001_initial'), ('auth', '0001_initial'), ('newsroom', '0001_initial'), ('subscribers', '0001_initial')]
  live_Story: module='newsroom.models' has_published=True str='Bridge bond passes council'
  hist_Story: module='__fake__' is_live=False has_published=False str='Story object (1)'

Look closely at those last two lines — they explain the #1 rule of writing Django data migrations (RunPython):

Notice one clever performance optimization inside ProjectState too: mutating a non-relational field (add_field, remove_field, alter_field on a plain CharField, CharField) passes "delay=True" to ProjectState.reload_model so Django avoids recursively re-rendering every related model in StateApps on every single field tweak!

Now that we know how Django builds a ProjectState by replaying migration history — and builds a second ProjectState from your live apps registry via ProjectState.from_apps — we can watch Django diff those two states to write new migrations next in Inside MigrationAutodetector.