---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`** (`django/db/migrations/graph.py:MigrationGraph`), replays every operation in memory onto a **`ProjectState`** (`django/db/migrations/state.py:ProjectState`), and dynamically synthesizes frozen historical model classes inside a private **`StateApps`** (`django/db/migrations/state.py:StateApps`) registry.

## `MigrationLoader`, `MigrationGraph`, and dependency DFS

When `"migrate"` or `"makemigrations"` starts, `MigrationLoader` (`django/db/migrations/loader.py: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` (`django/db/migrations/migration.py:Migration`) class, and stores `(app_label, migration_name) -> Migration` in `"disk_migrations"`.
2. **In the database (`MigrationRecorder.applied_migrations`, `django/db/migrations/recorder.py: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` (`django/db/migrations/graph.py: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` (`django/db/migrations/graph.py:MigrationGraph.forwards_plan`) and `MigrationGraph.backwards_plan` run `MigrationGraph.iterative_dfs` (`django/db/migrations/graph.py:MigrationGraph.iterative_dfs`) — a deterministic post-order depth-first search sorting parent keys so every dependency executes strictly before its dependents.

## `ProjectState`, `django/db/migrations/state.py:ModelState`, and synthetic `"__fake__"` models

Once the graph defines an exact replay order, `MigrationExecutor._create_project_state` (`django/db/migrations/executor.py:MigrationExecutor._create_project_state`) starts from an empty `ProjectState` (`models = {}`) and walks the plan calling `Migration.mutate_state` (`django/db/migrations/migration.py: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 `django/db/models/base.py:ModelState`) holding pure Python metadata: `"app_label"`, `"name"`, `"fields"` (unattached `Field` clones, `django/db/models/fields/__init__.py: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` (`django/db/migrations/state.py:ProjectState.apps`) constructs a **`StateApps`** (`django/db/migrations/state.py:StateApps`), a private subclass of `Apps` (`django/apps/registry.py:Apps`). `StateApps.render_multiple` loops over every `ModelState`, calling `ModelState.render` (`django/db/migrations/state.py: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`, `django/db/models/manager.py: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/"`:

```text recording=ch09-database
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_Story.__module__ == '__fake__'"` and `"hist_Story"` is synthesized purely from migration files, **`"hist_Story"` has NONE of your custom methods, properties, or `"StoryQuerySet"` methods** (`has_published=False`, and `str()` 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 `"newsroom.models.Story"` directly inside a `RunPython` migration 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 `"apps.get_model('newsroom', 'Story')"` from `StateApps`.

Notice one clever performance optimization inside `ProjectState` too: mutating a non-relational field (`add_field`, `remove_field`, `alter_field` on a plain `CharField`, `django/db/models/fields/__init__.py:CharField`) passes `"delay=True"` to `ProjectState.reload_model` (`django/db/migrations/state.py: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](autodetector.md).
