﻿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
37516	Migration optimizer doesn’t update CompositePrimaryKey.field_names when reducing RenameField into CreateModel	Toluwalase_HTE		"When the migration optimizer reduces a `RenameField` into a preceding `CreateModel`, `CreateModel.reduce()` renames the field and updates `unique_together`/`index_together` and `order_with_respect_to`, but it doesn't update `CompositePrimaryKey.field_names`. The resulting `CreateModel` has a primary key referencing a field that no longer exists, and applying it crashes.

The unoptimized path is correct: `ProjectState.rename_field()` was taught to update `field_names` in #35991, but the equivalent logic was never added to the optimizer.

Minimal reproduction:

{{{#!python
from django.db import migrations, models
from django.db.migrations.optimizer import MigrationOptimizer

operations = [
    migrations.CreateModel(
        ""Release"",
        [
            (""pk"", models.CompositePrimaryKey(""version"", ""name"")),
            (""version"", models.IntegerField()),
            (""name"", models.CharField(max_length=20)),
        ],
    ),
    migrations.RenameField(""Release"", ""version"", ""number""),
]
optimized = MigrationOptimizer().optimize(operations, ""app"")
}}}

Applying `operations` as written works and creates `PRIMARY KEY (""number"", ""name"")`.

`optimized` is a single `CreateModel` whose `pk` is still `CompositePrimaryKey(""version"", ""name"")` alongside a field named `number`. Applying it fails with:

{{{
django.core.exceptions.FieldDoesNotExist: Release has no field named 'version'
}}}

This affects `squashmigrations` whenever a migration contains a standalone `RenameField` of a composite primary key component, for example a hand-written migration. Migrations generated by the autodetector currently avoid the crash only because it also emits an `AlterField` for `pk` after the rename. As noted in #35991 (comment:2), that `AlterField` arguably shouldn't be generated in the first place, and once it isn't, regular squashes would hit this bug.

Reproduced on `main` (9e2e5a3). I'd like to work on a fix: update composite primary key references in the `RenameField` branch of `CreateModel.reduce()`, plus a regression test in `tests/migrations/test_optimizer.py`."	Bug	new	Migrations	dev	Normal		CompositePrimaryKey, squashmigrations, optimizer		Unreviewed	0	0	0	0	0	0
