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

# Inside MigrationAutodetector

How does makemigrations turn the difference between two `ProjectState` snapshots into ordered operations, detect renames, and simplify them with `MigrationOptimizer`?

When you run `"manage.py makemigrations"`, Django does **not** connect to your database at all! Instead, it constructs two in-memory `ProjectState` (`django/db/migrations/state.py:ProjectState`) objects — `"from_state"` by replaying every migration file on disk via `MigrationLoader.project_state`, and `"to_state"` by snapshotting your live `"models.py"` registry via `ProjectState.from_apps` (`django/db/migrations/state.py:ProjectState.from_apps`) — and hands both snapshots to **`MigrationAutodetector`** (`django/db/migrations/autodetector.py:MigrationAutodetector`).

## The 25-step diff pipeline inside `_detect_changes`

Open `MigrationAutodetector._detect_changes` (`django/db/migrations/autodetector.py:MigrationAutodetector._detect_changes`) and notice why its call order is rigid and deliberate:

1. **Partition and resolve:** Splits both states into concrete models, proxy models, and unmanaged models (`managed = False`), ignoring unmigrated apps, and calls `ProjectState.resolve_fields_and_relations` on both snapshots so foreign-key and `"through"` references are indexed symmetrically.
2. **Detect model renames first (`generate_renamed_models`):** Before emitting any `DeleteModel` or `CreateModel`, Django compares disappeared model names against newly appeared model names in the same app. If two models share matching deconstructed fields (or closely overlapping fields), Django asks its `MigrationQuestioner` (`ask_rename_model`) whether the model was renamed — recording the mapping in `"self.renamed_models"` so downstream field comparisons match the old and new models instead of generating a destructive drop-and-recreate!
3. **Model lifecycle and options:** Generates `DeleteModel`, `CreateModel`, proxy additions/deletions, `AlterModelOptions`, `AlterModelManagers`, and table comments.
4. **Field renames, indexes, constraints, and fields (strict order!):** Runs `create_renamed_fields` (comparing disappeared and added fields on the same model using `"deep_deconstruct"` — ignoring field names!), removes obsolete constraints and indexes *before* removing fields, emits `RenameField` and `RenameIndex`, removes obsolete `unique_together`, emits `RemoveField`, `AddField`, and `AlterField`, and finally adds new `unique_together`, indexes, constraints, and `AlterModelTable`.

Every generated operation is tagged with an internal `"_auto_deps"` list of `OperationDependency` records — for example, `"AddField"` on `"Story.desk"` declares a dependency on `"('newsroom', 'desk', None, True)"` (`CreateModel("Desk")`), while `"DeleteModel('Desk')"` depends on removing every foreign key pointing at `"Desk"` first.

## Topological sorting, cross-app chopping, and `MigrationOptimizer`

Generating operations in logical phases is not enough when models inside the same app point at each other, or when two apps (`"newsroom"` and `"subscribers"`) have mutual foreign keys. `MigrationAutodetector._detect_changes` finishes with three passes:

- **Intra-app topological sort (`MigrationAutodetector._sort_migrations`):** Feeds every operation in each app into Python's stdlib `graphlib.TopologicalSorter` along with its intra-app `"_auto_deps"`, producing a guaranteed-valid execution order (`graphlib.TopologicalSorter.static_order`) so `"Desk"` is created before `"Story"` references it.
- **Cross-app chopping (`MigrationAutodetector._build_migration_list`):** Walks each app's sorted operations in a loop. The instant an operation has an unsatisfied external dependency in *another* app, Django chops off all preceding satisfied operations into a `Migration` (`django/db/migrations/migration.py:Migration`, named `"auto_1"`), moves to the other app to satisfy the dependency, and comes back to cut `"auto_2"` if a circular cross-app reference requires splitting one app's changes across two migration files!
- **Operation reduction (**`MigrationOptimizer`**):** Finally, `_optimize_migrations` feeds every migration's operation list through **`MigrationOptimizer`** (`django/db/migrations/optimizer.py:MigrationOptimizer`).

Look at how tiny and elegant `MigrationOptimizer` is — the entire file is 69 lines! `MigrationOptimizer.optimize` runs `MigrationOptimizer.optimize_inner` in a fixed-point loop until a full pass produces an identical list. For each operation at index `i`, `optimize_inner` scans forward across subsequent operations `j` calling `Operation.reduce(other, app_label)` (`django/db/migrations/operations/base.py:Operation.reduce`):

- Returning a **`list`** replaces the pair with a shorter list — merging `CreateModel + AddField + AlterField` into a single `CreateModel`, or cancelling `CreateModel + DeleteModel` into `[]`!
- Returning **`True`** means `"operation"` can safely leapfrog past `"other"` (they touch unrelated models) to merge with a match further down the list.
- Returning **`False`** marks a **reduction barrier** — anything touching the same model/field, or any opaque `RunSQL` (`django/db/migrations/operations/special.py:RunSQL`) / `RunPython` (`django/db/migrations/operations/special.py:RunPython`) operation — preventing unsafe reordering across arbitrary SQL or Python side effects!

Once optimized, `MigrationWriter` (`django/db/migrations/writer.py:MigrationWriter`) deconstructs every operation and `Field` (`django/db/models/fields/__init__.py:Field`) via `OperationWriter.serialize` and writes clean formatted Python source to disk (auto-naming files like `0002_story_byline_alter_story_headline.py`).

Watch `MigrationAutodetector` diff a cloned `ProjectState` of `"desk/"` (adding `"byline"` and widening `"headline"` to `200` chars) and watch `MigrationOptimizer` collapse and hit a `RunSQL` barrier live:

```text recording=ch09-database
6. MigrationAutodetector diffing ProjectState and MigrationOptimizer
  detected_apps = ['newsroom']
    migration='0002_story_byline_alter_story_headline' dependencies=[('newsroom', '0001_initial')]
      op = Add field byline to story
      op = Alter field headline on story
  optimizer_merge: 3 ops -> 1 op (CreateModel fields=['id', 'level'])
  optimizer_cancel: Create+Delete -> 0 ops; with RunSQL barrier -> 3 ops
```

That explains a practical tip every Django team learns when running `"squashmigrations"`: if your squashed migration still contains fifty uncollapsed operations, look for a `RunPython` or `RunSQL` step sitting in the middle acting as an optimization barrier!

Generating migration files is only half the journey. When you finally run `"manage.py migrate"`, `MigrationExecutor` replays those operations against a live database through `BaseDatabaseSchemaEditor` — and on SQLite, altering a single `"max_length"` triggers a seven-statement full-table rebuild. We watch that happen next in [BaseDatabaseSchemaEditor and table rewrites](schema-editor.md).
