Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Received "ValueError: Found wrong number (0) of constraints for ..." during Django migration

While using Django 1.7 migrations, I came across a migration that worked in development, but not in production:

ValueError: Found wrong number (0) of constraints for table_name(a, b, c, d)

This is caused by an AlterUniqueTogether rule:

   migrations.AlterUniqueTogether(
         name='table_name',
         unique_together=set([('a', 'b')]),
   )

Reading up on bugs and such in the Django bug DB it seems to be about the existing unique_together in the db not matching the migration history.

How can I work around this error and finish my migrations?

like image 413
rrauenza Avatar asked Jan 12 '17 21:01

rrauenza


3 Answers

(Postgres and MySQL Answer)

If you look at your actual table (use \d table_name) and look at the indexes, you'll find an entry for your unique constraint. This is what Django is trying to find and drop. But it can't find an exact match.

For example,

"table_name_...6cf2a9c6e98cbd0d_uniq" UNIQUE CONSTRAINT, btree (d, a, b, c)

In my case, the order of the keys (d, a, b, c) did not match the constraint it was looking to drop (a, b, c, d).

I went back into my migration history and changed the original AlterUniqueTogether to match the actual order in the database.

The migration then completed successfully.

like image 173
rrauenza Avatar answered Nov 06 '22 23:11

rrauenza


I had a similar issue come up while I was switching over a CharField to become a ForeignKey. Everything worked with that process, but I was left with Django thinking it still needed to update the unique_together in a new migration. (Even though everything looked correct from inside postgres.) Unfortunately applying this new migration would then give a similar error:

ValueError: Found wrong number (0) of constraints for program(name, funder, payee, payer, location, category)

The fix that ultimately worked for me was to comment out all the previous AlterUniqueTogether operations for that model. The manage.py migrate worked without error after that.

like image 7
Ben Avatar answered Nov 07 '22 01:11

Ben


"unique_together in the db not matching the migration history" - Every time an index is altered on a table it checks its previous index and drops it. In your case it is not able to fetch the previous index.

Solution- 1.Either you can generate it manually 2.Or revert to code where previous index is used and migrate.Then finally change to new index in your code and run migration.(django_migration files to be taken care of)

like image 1
Vaishali Chuphal Avatar answered Nov 07 '22 00:11

Vaishali Chuphal