Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Created September 25, 2023 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jim-clark/ca07e91f9fbef54baf3e738b40c77ae6 to your computer and use it in GitHub Desktop.
Save jim-clark/ca07e91f9fbef54baf3e738b40c77ae6 to your computer and use it in GitHub Desktop.

Rolling Back Django Migrations

Django migrations can be unapplied to a database in the reverse order that they were applied using the following commands...

Listing the Migrations for a Specific Django App

Run the following to list the existing migrations for the main_app Django app:

python3 manage.py showmigrations main_app

...which will output something like this for the catcollector:

main_app
 [X] 0001_initial
 [X] 0002_feeding
 [X] 0003_toy_alter_feeding_options_alter_feeding_date
 [X] 0004_cat_toys
 [X] 0005_photo
 [X] 0006_cat_user

Rolling Back to a Specified Migration

Let's say that you wanted to modify, e.g., rename/add/remove or change the type of field, in the Photo model. To do so requires the migration created by adding the Photo model be rolled back (unapplied) using the following command:

👀 Warning: Rolling back migrations can result in the loss of data without warning. For example, the following will result in the removal of the entire photos table from the database!

python3 manage.py migrate main_app 0004

👀 Note that an IrreversibleError will occur if it's not possible to roll back a migration due to database integrity reasons.

The above command will unapply all migrations after the migration number 0004 (0004_cat_toys) and running the same showmigrations command will confirm that those migrations have been unapplied:

main_app
 [X] 0001_initial
 [X] 0002_feeding
 [X] 0003_toy_alter_feeding_options_alter_feeding_date
 [X] 0004_cat_toys
 [ ] 0005_photo
 [ ] 0006_cat_user

Rolling Back All Migrations

If you want to unapply all migrations for an app - and losing all data created thus far, here's the command:

python3 manage.py migrate main_app zero

Editing Migration(s)

Once a migration has been unapplied, it's possible to carefully edit the migration file, for example, to correct a field type.
After editing, the migration(s) may be ran again using the familiar migrate command:

python3 manage.py migrate

Deletion Migration(s)

It's also possible to delete the unapplied migration files, however, all unapplied migration files should be removed otherwise errors may result.

After deleting, it's also important to delete the __pycache__ folder that's inside of the migrations folder.

With the migration file(s) deleted, you may make the necessary changes to your model(s) and makemigrations/migrate afterwards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment