﻿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
37552	makemigrations crashes with KeyError: 'fields' when a field with db_column is renamed and a constraint without fields is altered	Konstantinos Giannopoulos	Konstantinos Giannopoulos	"When a field that has a `db_column` is renamed (keeping the same `db_column`), and in the same `makemigrations` run a constraint without a `fields` argument is altered, `makemigrations` crashes with `KeyError: 'fields'`. This affects `CheckConstraint` and `UniqueConstraint` defined with expressions only. Changing only the constraint's `violation_error_message` is enough.

Initial model (migrated):
{{{#!python
class Product(models.Model):
    code = models.CharField(max_length=20, unique=True, db_column=""product_code"")
    price = models.DecimalField(max_digits=8, decimal_places=2)

    class Meta:
        constraints = [
            models.CheckConstraint(
                condition=models.Q(price__gte=0),
                name=""price_not_negative"",
                violation_error_message=""Invalid price."",
            ),
        ]
}}}

Rename `code` to `sku` (same `db_column`) and change the constraint's message:
{{{#!python
class Product(models.Model):
    sku = models.CharField(max_length=20, unique=True, db_column=""product_code"")
    price = models.DecimalField(max_digits=8, decimal_places=2)

    class Meta:
        constraints = [
            models.CheckConstraint(
                condition=models.Q(price__gte=0),
                name=""price_not_negative"",
                violation_error_message=""Price cannot be negative."",
            ),
        ]
}}}

Running `makemigrations` and answering ""y"" to the rename question crashes:
{{{
  File ""django/db/migrations/autodetector.py"", line 199, in _detect_changes
    self.create_altered_constraints()
  File ""django/db/migrations/autodetector.py"", line 1557, in create_altered_constraints
    and not self._constraint_should_be_dropped_and_recreated(
  File ""django/db/migrations/autodetector.py"", line 1522, in _constraint_should_be_dropped_and_recreated
    new_fields = new_kwargs[""fields""]
                 ~~~~~~~~~~^^^^^^^^^^
KeyError: 'fields'
}}}

Expected: a migration with `RenameField` and `AlterConstraint`. Each change on its own works, and making them in two separate `makemigrations` runs works too. The rename and the constraint do not need to be on the same model: a rename on any model in the project, together with an altered `CheckConstraint` or expression-based `UniqueConstraint` anywhere, triggers the crash.

`MigrationAutodetector._constraint_should_be_dropped_and_recreated()` reads `new_kwargs[""fields""]` for every rename that keeps its `db_column`, but constraints without fields don't have that key.

Regression in b2407e4d7d25e4a5839bb512cb2fdf71e9e30a21 (#35305). The commit before it generates `RenameField` + `AlterConstraint` for this case.

A fix is to skip the field-name replacement when `""fields""` is not in `new_kwargs`. Regression tests for `tests/migrations/test_autodetector.py`:
{{{#!python
def test_rename_field_preserve_db_column_alter_check_constraint(self):
    def product(field_name, message):
        return ModelState(
            ""app"", ""Product"",
            [(""id"", models.AutoField(primary_key=True)),
             (field_name, models.CharField(max_length=20, db_column=""product_code"")),
             (""price"", models.DecimalField(max_digits=8, decimal_places=2))],
            options={""constraints"": [
                models.CheckConstraint(
                    condition=models.Q(price__gte=0),
                    name=""price_not_negative"",
                    violation_error_message=message,
                ),
            ]},
        )

    changes = self.get_changes(
        [product(""code"", ""Invalid price."")],
        [product(""sku"", ""Price cannot be negative."")],
        MigrationQuestioner({""ask_rename"": True}),
    )
    self.assertOperationTypes(changes, ""app"", 0, [""RenameField"", ""AlterConstraint""])

def test_rename_field_preserve_db_column_alter_expression_unique_constraint(self):
    def author(field_name):
        return ModelState(
            ""app"", ""Author"",
            [(""id"", models.AutoField(primary_key=True)),
             (field_name, models.CharField(max_length=20, db_column=""code""))],
        )

    def book(message):
        return ModelState(
            ""app"", ""Book"",
            [(""id"", models.AutoField(primary_key=True)),
             (""title"", models.CharField(max_length=100))],
            options={""constraints"": [
                models.UniqueConstraint(
                    Lower(""title""),
                    name=""unique_lower_title"",
                    violation_error_message=message,
                ),
            ]},
        )

    changes = self.get_changes(
        [author(""code""), book(""Duplicate title."")],
        [author(""slug""), book(""A book with this title already exists."")],
        MigrationQuestioner({""ask_rename"": True}),
    )
    self.assertOperationTypes(changes, ""app"", 0, [""RenameField"", ""AlterConstraint""])
}}}

Related: #37551 (same method; a rename on one model is wrongly applied to another model's constraint). The two can be fixed in one pull request.

A small project reproducing this end to end is attached."	Bug	assigned	Migrations	6.0	Release blocker		KeyError, CheckConstraint, db_column, RenameField, autodetector	Konstantinos Giannopoulos	Unreviewed	0	0	0	0	0	0
