How To Rerun A Django Migration

How To Rerun A Django Migration

By admin ·
1

Fake back to the migration immediately before the one you want to rerun

First, imagine the migration history for myapp looks like this:

$ ./manage.py showmigrations myapp
myapp
...
[x] 0004_the_migration_right_before
[x] 0005_the_migration_i_want_to_rerun
[x] 0006_a_migration_i_dont_care_about
...
[x] 0010_the_latest_migration

It’s wise to visualize the migration history before messing with migrations. When we’re finished with this process we can ensure the final migration state matches the original state.

So the latest migration is 0010_the_latest_migration and we want to rerun 0005_the_migration_i_want_to_rerun.

We’ll use the --fake flag to “fake” back to the migration before the one we want to rerun. We’ll also need to specify the target app for the migration, which in this case is myapp.

./mange.py migrate --fake myapp 0004_the_migration_right_before

Keep in mind, this is an advanced feature that modifies the migration state. It can cause issues that require manual recovery.

2

Rerun the target migration

Now we can run only our target migration:

./mange.py migrate myapp 0005_the_migration_i_want_to_rerun
3

Fake back to the latest migration

Now, in order to restore the original migration state, we need to fake back to the latest migration:

./mange.py migrate --fake myapp 0010_the_latest_migration

We can confirm our migration history looks correct by running the following, and comparing to the original state:

./manage.py showmigrations myapp
myapp
...
[x] 0004_the_migration_right_before
[x] 0005_the_migration_i_want_to_rerun
[x] 0006_a_migration_i_dont_care_about
...
[x] 0010_the_latest_migration