Categories
Django Python

Django: Handling broken migrations

Often for one reason or another, migrations don’t apply properly and we have to fix them manually. If there’s a faulty migration that throws errors when run, we first have to identify what went wrong. Very often on MySQL, we see half applied migrations (probably because MySQL doesn’t have transactions?). In this case we need to do the other half ourselves.

We can easily connect to the database prompt by typing the dbshell command.

The command opens the shell for the respective database engine using the configurations provided in the settings file. That is you don’t have to remember the username or password for the database connection.

Now you have to fix the issues and then you can try running the migration again. In case it fails again, you should alter the database to match the state the migration would have created. For example, if the migration was supposed to alter a column from store_type to store_type_id (from a char field to foreign keys), you have to manually run the query, something like:

Then you have to fake the migration. When a migration is run, Django stores the name of the migration in a table. It helps track which migrations have already run and which needs to be run. When we fake a migration, Django stores the faked migration name in that table without actually running it. If we don’t do this, when we next run migrate command, Django will try to run this migration again and fail.

This is how we fake it:

You can also specify one particular migration when you have multiple migrations running.

One reply on “Django: Handling broken migrations”

check whether there are differences between the models and the migration history (this is more reliable with the new Django migrations, South was an external tool and had not all of the possibilities) (e.g.

Comments are closed.