Django doesn't automatically remove the uniqueness constraint from the database when changing it in a subsequent migration?

I had a Model A with a field unique=True and migrated to Mysql database after couple of migrations I decided to remove the constraint and changed unique=False and makemigration and migrated successfuly however I see that in the table the field is still unique and I had to drop the constraint in SQL from table. why django migration doesn’t applied in case of droping unique constraint?

Django is able to do that - see the RemoveConstraint migration operation.

Understanding why Django didn’t generate this operation would probably require going through all the existing migrations to see what happened.

If you’ve got other pre-existing databases where these migrations need to be applied, you could add a manual migration to explicitly remove the constraint.

What you might also want to do is run your migrations on a brand new database, to see if it creates the structure you want. If it does (there’s no constraint on that table), then I’m not sure it’s worth the effort to try and figure out “why”, unless you’re really curious about it.

Thanks for reply Ken. I use python manage.py makemigrations and then python manage.py migrate on every change on database and everything was fine. untill I changed a model field from unique=True to unique=False and in the migration file generated there was no RemoveConstraint automatically. so after searching awile I found I should do it manuly this time.
Is this an exception in django migration? Im curiose about the logic behind this. is there any other exceptions which should be done manually?

Unfortunately, this fits into the category of “Works for me”. I’ve tried to recreate what you’re describing here, and in every case, makemigrations makes the changes to the database.

That’s why I said earlier that understanding why it’s not working for you would require a complete review of all migrations along with a dump of your current db schema.

1 Like