Opened 3 years ago

Closed 3 years ago

#28916 closed Bug (duplicate)

Changing the type of a ForeignKey and changing unique_together creates migrations in the wrong order, causing migrations to fail

Reported by: fredley Owned by:
Component: Migrations Version: 2.0
Severity: Normal Keywords: migrations
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by fredley)

models.py before:

class MyModel(models.Model):
    fka = models.ForeignKey(SomethingA, ...)
    date = models.DateField()

    class Meta:
        unique_together = ('fka', 'date')

models.py after:

class MyModel(models.Model):
    fkb = models.ForeignKey(SomethingB, ...)
    date = models.DateField()

    class Meta:
        unique_together = ('fkb', 'date')

This can result in an automatically created migration (using manage.py makemigrations) that looks like this:

operations = [
    migrations.AddField(
        model_name='mymodel',
        name='fkb',
        field=models.ForeignKey(... to='myapp.somethingb'),
    ),
    migrations.RemoveField(
        model_name='mymodel',
        name='fka',
    ),
    migrations.AlterUniqueTogether(
        name='mymodel',
        unique_together={('fkb', 'date')},
    ),
]

This migration fails, because AlterUniqueTogether needs to come before RemoveField, as it references fka. This is hard to debug, and can only be fixed by manually reordering the migration operations.

Change History (5)

comment:1 Changed 3 years ago by fredley

Component: UncategorizedMigrations

comment:2 Changed 3 years ago by fredley

Description: modified (diff)

comment:3 Changed 3 years ago by Junji Wei

Owner: changed from nobody to Junji Wei
Status: newassigned

comment:4 Changed 3 years ago by Junji Wei

Owner: Junji Wei deleted
Status: assignednew

comment:5 Changed 3 years ago by Ramiro Morales

Resolution: duplicate
Status: newclosed

I think this is a duplicate of #28862.

Note: See TracTickets for help on using tickets.
Back to Top