3 | | I have a model, already created through previous migrations, and in a new migration I added a new field with a UniqueConstraint. |
4 | | The model looks like this (the new field is 'type') : |
| 3 | I have a model, already created through previous migrations, and in a new migration I added a new field with an UniqueConstraint. The migrations script try to create the constraint first and then the new field, resulting an error : |
| 4 | |
| 5 | {{{ |
| 6 | django.core.exceptions.FieldDoesNotExist: NewModel has no field named 'category' |
| 7 | }}} |
| 8 | |
| 9 | |
| 10 | To reproduce the bug : |
| 11 | |
| 12 | 1. Create a project with two models linked together with a One-to-Many relation and an unique constraint : |
| 13 | |
| 14 | {{{ |
| 15 | class Type(models.Model): |
| 16 | name = models.CharField(max_length=10) |
| 17 | |
| 18 | |
| 19 | class Model(models.Model): |
| 20 | name = models.CharField(max_length=10) |
| 21 | type = models.ForeignKey(Type, on_delete=models.SET_NULL, null=True) |
| 22 | date = models.DateField(auto_now=True) |
| 23 | |
| 24 | class Meta: |
| 25 | constraints = ( |
| 26 | models.UniqueConstraint(fields=('date', 'type'), name='unique_type_for_date'), |
| 27 | ) |
| 28 | }}} |
| 29 | |
| 30 | 2. Create a migration file with `manage.py makemigrations` |
| 31 | |
| 32 | 3. Add a new model with another One-to-Many relation and unique constraint. The models looks like this : |
9 | | name = models.CharField() |
10 | | date = models.DateField() |
11 | | type = models.ForeignKey(OtherModel) |
| 45 | name = models.CharField(max_length=10) |
| 46 | type = models.ForeignKey(Type, on_delete=models.SET_NULL, null=True) |
| 47 | category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) |
| 48 | date = models.DateField(auto_now=True) |
22 | | django.core.exceptions.FieldDoesNotExist: DailyTask has no field named 'type' |
| 62 | class Migration(migrations.Migration): |
| 63 | |
| 64 | dependencies = [ |
| 65 | ('app', '0001_initial'), |
| 66 | ] |
| 67 | |
| 68 | operations = [ |
| 69 | migrations.CreateModel( |
| 70 | name='Category', |
| 71 | fields=[ |
| 72 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), |
| 73 | ('name', models.CharField(max_length=10)), |
| 74 | ], |
| 75 | ), |
| 76 | migrations.AddConstraint( |
| 77 | model_name='model', |
| 78 | constraint=models.UniqueConstraint(fields=('date', 'category'), name='unique_category_for_date'), |
| 79 | ), |
| 80 | migrations.AddField( |
| 81 | model_name='model', |
| 82 | name='category', |
| 83 | field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='app.category'), |
| 84 | ), |
| 85 | ] |