﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
37572	Migration optimizer fails to update self-referential relations when CreateModel absorbs RenameModel	Patel Namraa	Patel Namraa	"The migration optimizer fails to update self-referential relationships when a `CreateModel` operation absorbs a subsequent `RenameModel` operation.

When 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.

This can result in an invalid squashed migration that references the old model name.

**Reproduction**

Consider the following migration operations:

{{{
operations = [
    migrations.CreateModel(
        ""Tree"",
        [
            (""id"", models.AutoField(primary_key=True)),
            (
                ""parent"",
                models.ForeignKey(
                    ""app.Tree"",
                    models.CASCADE,
                    null=True,
                ),
            ),
        ],
    ),
    migrations.RenameModel(""Tree"", ""Node""),
]
}}}

When these operations are optimized using `MigrationOptimizer`, the resulting `CreateModel` operation is named `Node`, but the `parent` field still references `app.Tree`.

**Actual behavior**

The optimized operation contains:

{{{
CreateModel(
    name=""Node"",
    fields=[
        (""parent"", models.ForeignKey(""app.Tree"", ...)),
    ],
)
}}}

The reference to `app.Tree` is stale because the model has been renamed to `Node`.

When the original migrations are replaced by the squashed migration and applied to a fresh database, Django can fail with:

{{{
ValueError: Related model 'app.tree' cannot be resolved
}}}

It can also cause `makemigrations --check` to detect an unnecessary schema change.

If another model later reuses the old name, the stale reference can potentially resolve to an unrelated model instead.

**Expected behavior**

When `CreateModel.reduce()` absorbs a `RenameModel` operation, all self-referential relationships should be updated to reference the renamed model.

For the example above, the optimized operation should contain:

{{{
CreateModel(
    name=""Node"",
    fields=[
        (""parent"", models.ForeignKey(""app.Node"", ...)),
    ],
)
}}}

The optimized and unoptimized migration sequences should produce equivalent project states.

**Additional affected cases**

The same problem occurs with self-referential `ManyToManyField` relationships.

**Technical details**

The issue is in `django/db/migrations/operations/models.py`, inside `CreateModel.reduce()`.

The current implementation handles the rename using:

{{{
return [replace(self, name=operation.new_name)]
}}}

This changes the model name without repointing relationships inside its fields.

The normal `RenameModel` operation already handles relationship updates through `ProjectState.rename_model()`, but this behavior is missing when the optimizer absorbs the rename into `CreateModel`.

**Proposed fix**

Update `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.

The fields should be cloned before modification to avoid mutating the original migration operation.

**Regression tests**

The following cases should be covered:

1. A self-referential `ForeignKey` when `CreateModel` absorbs `RenameModel`.
2. A self-referential `ManyToManyField` when `CreateModel` absorbs `RenameModel`.
3. A renamed model whose old name is subsequently reused by another model, ensuring the original relationship does not resolve to the unrelated model.

**Related ticket**

Ticket #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."	Bug	assigned	Migrations	6.1	Normal			Patel Namraa	Unreviewed	0	0	0	0	0	0
