Opened 5 weeks ago

Last modified 4 days ago

#29123 new Bug

Changing an IntegerField to a ForeignKey generates incorrectly ordered migration operations if the field is in unique_together

Reported by: Ed Morley Owned by: nobody
Component: Migrations Version: master
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Ed Morley)

Replacing an integer field with a foreign key of the same name, results in an OperationalError when creating/applying the migration.

This affects Django master + v1.11.10, and both the SQLite and MySQL backends (others not tested).


  1. Git clone
  2. pip install
  3. ./ migrate
  4. cp testapp/ testapp/
  5. ./ makemigrations --name broken_migration
  6. ./ migrate


New migration is created/applied successfully, which converts from the original model to the new model.


The new migration incorrectly lists the AddField operation before the RemoveField operation...

    operations = [
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='testapp.Foo'),
            unique_together={('name', 'foo')},

Which results in an exception at step 6...

$ ./ migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, testapp
Running migrations:
  Applying testapp.0002_broken_migration...Traceback (most recent call last):
  File ".../site-packages/django/db/backends/", line 83, in _execute
    return self.cursor.execute(sql)
  File ".../site-packages/django/db/backends/sqlite3/", line 290, in execute
    return Database.Cursor.execute(self, query)
sqlite3.OperationalError: duplicate column name: foo_id

Additional notes:

  • Without the unique_together on model Bar, the bug does not occur.
  • This affects both the SQLite backend and the MySQL backend (others not tested).
  • At time of testing, django master was at revision 6d794fb76212bb8a62fe2cd97cff173054e1c626.
  • The above was using Python 3.6.2.

Change History (2)

comment:1 Changed 5 weeks ago by Ed Morley

Description: modified (diff)

comment:2 Changed 5 weeks ago by Tim Graham

Summary: Generated migration orders Add/Remove Field incorrectly, causing OperationalErrorChanging an IntegerField to a ForeignKey generates incorrectly ordered migration operations if the field is in unique_together
Triage Stage: UnreviewedAccepted

I didn't attempt to reproduce but the report looks credible.

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