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/ how "manage or "manage 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:
- On disk (
MigrationLoader): Scans every app in.load_disk "INSTALLED_APPS"for a"migrations"package, imports each non-underscore Python module, extracts itsMigrationclass, and stores(app_label, migration_name) -> Migrationin"disk_migrations". - In the database (
MigrationRecorder,.applied_migrations MigrationRecorder): Queries the.applied_migrations "django_migrations"table — the only tableMigrationLoaderinspects in the database — to learn which(app, name)pairs are already applied.
MigrationLoader 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) 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 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 and MigrationGraph run MigrationGraph — 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 starts from an empty ProjectState (models = {}) and walks the plan calling Migration 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 constructs a StateApps, a private subclass of Apps. StateApps loops over every ModelState, calling ModelState, 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 — running ModelBase inside that isolated StateApps registry!
Watch MigrationLoader, MigrationGraph, and live vs. historical "Story" models execute on "desk/":
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):
- Because
"hist_Storyand.__module__ == '__fake__'" "hist_Story"is synthesized purely from migration files,"hist_Story"has NONE of your custom methods, properties, or"StoryQuerySet"methods (has_published=False, andstr()falls back to"Story object (1)"instead of"Bridge bond passes council"!). - That detachment is a safety feature, not a limitation: if you imported live
"newsroomdirectly inside a.models .Story" RunPythonmigration and later added a new column to"Story", replaying that old migration on a fresh database would generate"SELECT"queries referencing a column that does not exist yet! Always fetch models via"appsfrom.get_model('newsroom', 'Story')" StateApps.
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 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 — we can watch Django diff those two states to write new migrations next in Inside MigrationAutodetector.