9.6 Connections, transactions, and migrations
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, Django does not connect to your database at all! Instead, it constructs two in-memory ProjectState objects — "from_state" by replaying every migration file on disk via MigrationLoader, and "to_state" by snapshotting your live "models.py" registry via ProjectState — and hands both snapshots to MigrationAutodetector.
The 25-step diff pipeline inside _detect_changes
Open MigrationAutodetector and notice why its call order is rigid and deliberate:
- Partition and resolve: Splits both states into concrete models, proxy models, and unmanaged models (
managed = False), ignoring unmigrated apps, and callsProjectStateon both snapshots so foreign-key and.resolve_fields_and_relations "through"references are indexed symmetrically. - Detect model renames first (
generate_renamed_models): Before emitting anyDeleteModelorCreateModel, 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 itsMigrationQuestioner(ask_rename_model) whether the model was renamed — recording the mapping in"selfso downstream field comparisons match the old and new models instead of generating a destructive drop-and-recreate!.renamed_models" - Model lifecycle and options: Generates
DeleteModel,CreateModel, proxy additions/deletions,AlterModelOptions,AlterModelManagers, and table comments. - 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, emitsRenameFieldandRenameIndex, removes obsoleteunique_together, emitsRemoveField,AddField, andAlterField, and finally adds newunique_together, indexes, constraints, andAlterModelTable.
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 finishes with three passes:
- Intra-app topological sort (
MigrationAutodetector): Feeds every operation in each app into Python’s stdlib._sort_migrations graphlibalong with its intra-app.TopologicalSorter "_auto_deps", producing a guaranteed-valid execution order (graphlib) so.TopologicalSorter .static_order "Desk"is created before"Story"references it. - Cross-app chopping (
MigrationAutodetector): 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._build_migration_list Migration(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_migrationsfeeds every migration’s operation list throughMigrationOptimizer.
Look at how tiny and elegant MigrationOptimizer is — the entire file is 69 lines! MigrationOptimizer runs MigrationOptimizer 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:
- Returning a
listreplaces the pair with a shorter list — mergingCreateModel + AddField + AlterFieldinto a singleCreateModel, or cancellingCreateModel + DeleteModelinto[]! - Returning
Truemeans"operation"can safely leapfrog past"other"(they touch unrelated models) to merge with a match further down the list. - Returning
Falsemarks a reduction barrier — anything touching the same model/field, or any opaqueRunSQL/RunPythonoperation — preventing unsafe reordering across arbitrary SQL or Python side effects!
Once optimized, MigrationWriter deconstructs every operation and Field via OperationWriter and writes clean formatted Python source to disk (auto-naming files like 0002_story_byline_alter_story_headline).
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:
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, 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.