Skip to content

unique_together constraint not restored after field alteration when field has unique=True #494

Description

When a field has both unique=True AND participates in a unique_together constraint, altering that field (e.g., changing its type or nullability) causes the unique_together constraint to be dropped but not restored. Only the single-field unique constraint is restored.

In mssql/schema.py, the _alter_field method's restoration logic for unique_together is inside an else block that only executes when the field does NOT have unique=True.

Steps to Reproduce

  1. Create a model with:
    • Field a with unique=True
    • Field b
    • unique_together = (('a', 'b'),) in Meta
class MyModel(models.Model):
    a = models.CharField(max_length=20, unique=True)
    b = models.CharField(max_length=20)

    class Meta:
        unique_together = (('a', 'b'),)
  1. Create a migration that alters field a (e.g., changes max_length):
operations = [
    migrations.AlterField(
        model_name='mymodel',
        name='a',
        field=models.CharField(max_length=40, unique=True),  # changed from max_length=20
    ),
]
  1. Run the migration
  2. Check database constraints using introspection or SQL Server Management Studio

Expected Behavior

After altering field a, both constraints should exist in the database:

  1. Single-field unique constraint on column a
  2. Multi-field unique constraint on columns (a, b) from unique_together

Actual Behavior

Only the single-field unique constraint on a is restored. The unique_together constraint on (a, b) is lost permanently.

Django Versions Affected

All supported versions

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: schema-migrationsDDL, migrations, indexes, constraints, schema introspectionbugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions