Opened 64 minutes ago

Last modified 55 minutes ago

#37552 assigned Bug

makemigrations crashes with KeyError: 'fields' when a field with db_column is renamed and a constraint without fields is altered

Reported by: Konstantinos Giannopoulos Owned by: Konstantinos Giannopoulos
Component: Migrations Version: 6.0
Severity: Release blocker Keywords: KeyError, CheckConstraint, db_column, RenameField, autodetector
Cc: Konstantinos Giannopoulos Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

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

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:

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:

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.

Attachments (1)

sample_shop_app.zip​ (8.8 KB ) - added by Konstantinos Giannopoulos 64 minutes ago.

Download all attachments as: .zip

Change History (3)

by Konstantinos Giannopoulos, 64 minutes ago

Attachment: sample_shop_app.zip​ added

comment:1 by Konstantinos Giannopoulos, 62 minutes ago

If this ticket (and ticket #37551), are accepted, i can work on a PR for the fixes.

comment:2 by Konstantinos Giannopoulos, 55 minutes ago

Owner: set to Konstantinos Giannopoulos
Status: new → assigned
Note: See TracTickets for help on using tickets.
Back to Top