Changes between Initial Version and Version 1 of Ticket #37572


Ignore:
Timestamp:
Dec 5, 2026, 4:21:44 AM (24 minutes ago)
Author:
Patel Namraa
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #37572 – Description

    initial v1  
     1The migration optimizer fails to update self-referential relationships when a `CreateModel` operation absorbs a subsequent `RenameModel` operation.
     2
     3When a model contains a self-referential `ForeignKey` or `ManyToManyField` and is subsequently renamed, `CreateModel.reduce()` optimizes the `RenameModel` operation by replacing the model name. However, references inside the model's fields are not updated to reflect the new model name.
     4
     5This can result in an invalid squashed migration that references the old model name.
     6
     7**Reproduction**
     8
     9Consider the following migration operations:
     10
     11{{{
     12operations = [
     13    migrations.CreateModel(
     14        "Tree",
     15        [
     16            ("id", models.AutoField(primary_key=True)),
     17            (
     18                "parent",
     19                models.ForeignKey(
     20                    "app.Tree",
     21                    models.CASCADE,
     22                    null=True,
     23                ),
     24            ),
     25        ],
     26    ),
     27    migrations.RenameModel("Tree", "Node"),
     28]
     29}}}
     30
     31When these operations are optimized using `MigrationOptimizer`, the resulting `CreateModel` operation is named `Node`, but the `parent` field still references `app.Tree`.
     32
     33**Actual behavior**
     34
     35The optimized operation contains:
     36
     37{{{
     38CreateModel(
     39    name="Node",
     40    fields=[
     41        ("parent", models.ForeignKey("app.Tree", ...)),
     42    ],
     43)
     44}}}
     45
     46The reference to `app.Tree` is stale because the model has been renamed to `Node`.
     47
     48When the original migrations are replaced by the squashed migration and applied to a fresh database, Django can fail with:
     49
     50{{{
     51ValueError: Related model 'app.tree' cannot be resolved
     52}}}
     53
     54It can also cause `makemigrations --check` to detect an unnecessary schema change.
     55
     56If another model later reuses the old name, the stale reference can potentially resolve to an unrelated model instead.
     57
     58**Expected behavior**
     59
     60When `CreateModel.reduce()` absorbs a `RenameModel` operation, all self-referential relationships should be updated to reference the renamed model.
     61
     62For the example above, the optimized operation should contain:
     63
     64{{{
     65CreateModel(
     66    name="Node",
     67    fields=[
     68        ("parent", models.ForeignKey("app.Node", ...)),
     69    ],
     70)
     71}}}
     72
     73The optimized and unoptimized migration sequences should produce equivalent project states.
     74
     75**Additional affected cases**
     76
     77The same problem occurs with self-referential `ManyToManyField` relationships.
     78
     79**Technical details**
     80
     81The issue is in `django/db/migrations/operations/models.py`, inside `CreateModel.reduce()`.
     82
     83The current implementation handles the rename using:
     84
     85{{{
     86return [replace(self, name=operation.new_name)]
     87}}}
     88
     89This changes the model name without repointing relationships inside its fields.
     90
     91The normal `RenameModel` operation already handles relationship updates through `ProjectState.rename_model()`, but this behavior is missing when the optimizer absorbs the rename into `CreateModel`.
     92
     93**Proposed fix**
     94
     95Update `CreateModel.reduce()` to identify self-referential field relationships using `field_references()` and repoint their `remote_field.model` and `remote_field.through` references to the new model name before returning the optimized operation.
     96
     97The fields should be cloned before modification to avoid mutating the original migration operation.
     98
     99**Regression tests**
     100
     101The following cases should be covered:
     102
     1031. A self-referential `ForeignKey` when `CreateModel` absorbs `RenameModel`.
     1042. A self-referential `ManyToManyField` when `CreateModel` absorbs `RenameModel`.
     1053. A renamed model whose old name is subsequently reused by another model, ensuring the original relationship does not resolve to the unrelated model.
     106
     107**Related ticket**
     108
     109Ticket #32263 covers a related migration optimizer issue involving references from another model to a renamed model. This report concerns a different case: self-referential relationships within the model being renamed.
Back to Top