Received “ValueError: Found wrong number (0) of constraints for …” during Django migration

和自甴很熟 提交于 2019-12-01 13:47:31

问题


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?


回答1:


(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.




回答2:


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.




回答3:


Also worth checking that you only have the expected number of Unique indexes for the table in question.

For example, if your table has multiple Unique indexes, then you should delete them to make sure you have only 1 (or whatever the number of expected Unique indexes is) pre-migration index present.

To check how many Unique indexes are there for a given table in PostgreSQL:

SELECT *
FROM information_schema.table_constraints AS c
WHERE
    c.table_name = '<table_name>'
    and c.constraint_type = 'UNIQUE'


来源:https://stackoverflow.com/questions/41623515/received-valueerror-found-wrong-number-0-of-constraints-for-during-djan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!