Django 6.1.3

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.py makemigrations", 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.project_state, and "to_state" by snapshotting your live "models.py" registry via ProjectState.from_apps — and hands both snapshots to MigrationAutodetector.

The 25-step diff pipeline inside _detect_changes

Open 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:

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):

Once optimized, MigrationWriter deconstructs every operation and 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:

Recorded on Django 6.1.3 ch09-database script
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.