How to Rerun a Django Migration

John John (304)
2 minutes

By default, Django migrations are run only once. But sometimes we need to rerun a Django migration, especially when testing custom migrations during development. This guide will show you how to do just that.

Posted in these interests:
h/django6 guides
h/python67 guides

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.

Now we can run only our target migration:

./mange.py migrate myapp 0005_the_migration_i_want_to_rerun

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
Dayne Dayne (57)
0

Django forms are an excellent way to manage user input in a Django application. Once you learn how to wield them, you'll never go back to manually coding a form tag and handling the response.