Opened 7 years ago

Closed 7 years ago

#25551 closed Bug (fixed)

makemigrations when adding a ForeignKey to a newly created model along with a unique_together constraint must create fields before the unique_together constraint

Reported by: Suriya Subramanian Owned by: avojnovicDk
Component: Migrations Version: 1.8
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


When adding a new model and a ForeignKey to it as well a unique_together constraint for the ForeignKey field, Django migrations should create the field before applying the unique_together constraint.

In the example below, I am adding a new Author model, a field to this model and a unique_together constraint for this field.

 from django.db import models
+class Author(models.Model):
+    name = models.CharField(max_length=255)
 class Book(models.Model):
     name = models.CharField(max_length=255)
+    author = models.ForeignKey(Author, null=True)
+    class Meta:
+        unique_together = (
+            ('name', 'author'),
+        )

Django's migrations framework produces the following summary output:

Migrations for 'testapp':
    - Create model Author
    - Alter unique_together for book (1 constraint(s))
    - Add field author to book

Here's the relevant portion of the migrations file:

    operations = [
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=255)),
            unique_together=set([('name', 'author')]),
            field=models.ForeignKey(to='testapp.Author', null=True),

This migration fails with the following stacktrace:

Operations to perform:
  Apply all migrations: testapp
Running migrations:
  Rendering model states... DONE
  Applying testapp.0002_auto_20151013_1354...Traceback (most recent call last):
  File "./", line 10, in <module>
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/core/management/", line 351, in execute_from_command_line
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/core/management/", line 343, in execute
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/core/management/", line 394, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/core/management/", line 445, in execute
    output = self.handle(*args, **options)
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/core/management/commands/", line 222, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/db/migrations/", line 110, in migrate
    self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/db/migrations/", line 148, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/db/migrations/", line 115, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/db/migrations/operations/", line 359, in database_forwards
    getattr(new_model._meta, self.option_name, set()),
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/", line 219, in alter_unique_together
    self._remake_table(model, override_uniques=new_unique_together)
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/", line 140, in _remake_table
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/db/backends/base/", line 272, in create_model
    columns = [model._meta.get_field(field).column for field in fields]
  File "/home/vagrant/testunique-env/local/lib/python2.7/site-packages/django/db/models/", line 554, in get_field
    raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: Book has no field named u'author'

Change History (6)

comment:1 Changed 7 years ago by Tim Graham

Triage Stage: UnreviewedAccepted

Seems similar to #22035 but I can reproduce the issue on master.

comment:2 Changed 7 years ago by avojnovicDk

Owner: changed from nobody to avojnovicDk
Status: newassigned

comment:3 Changed 7 years ago by avojnovicDk

Has patch: set

This happens for the very specific edge case: If you create a model, make migrations for that model, and then add a foreign key to another model that didn't exist previously with unique together, the order of the action in the new migration will not be correct: it will try to alter unique together and then add the field used in unique together.
I made PR with fix for this.

comment:4 Changed 7 years ago by Tim Graham

Patch needs improvement: set

comment:5 Changed 7 years ago by avojnovicDk

Patch needs improvement: unset

comment:6 Changed 7 years ago by Tim Graham <timograham@…>

Resolution: fixed
Status: assignedclosed

In 73a6ab63:

Fixed #25551 -- Fixed migration operations ordering when adding fields and a unique_together constraint.

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