[Django]-Django migration IntegrityError: invalid foreign key (but the data exists)

2πŸ‘

βœ…

This problem is caused by the mentioned Django bug, but if you get the migration error, your database is broken already.

When you dump the DB to SQL, you can see REFERENCES statements which point to tables ending in __old, but these tables do not actually exist:

$> sqlite3 mydb.db .dump | grep '__old'

CREATE TABLE IF NOT EXISTS "company" [...]"account_id" integer NULL REFERENCES "account__old" ("id") [...]

Fortunately, the DB can be fixed easily, by just removing the __old and dumping into a new database. This can be automated with sed:

sqlite3 broken.db .dump | sed 's/REFERENCES "\(.[^"]*\)__old"/REFERENCES "\1"/g' | sqlite3 fixed.db
πŸ‘€chrisv

0πŸ‘

It is not an ideal solution, but you can manually delete the row from the database or set the value of the foreign key to a temporary value, migrate and then restore the original value.

Leave a comment