Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Last active July 14, 2025 13:06
Show Gist options
  • 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_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 Toy model. To do so requires the migration created by adding the Toy 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 toys table from the database!

python3 manage.py migrate main_app 0002

πŸ‘€ 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 0002 (0002_feeding.py). Running the same showmigrations command will confirm that those migrations have been unapplied:

main_app
 [X] 0001_initial
 [X] 0002_feeding
 [ ] 0003_toy_alter_feeding_options_alter_feeding_date
 [ ] 0004_cat_toys
 [ ] 0005_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

Deleting and Replacing Migration(s)

Once migrations has been unapplied, it's safe to:

  1. Delete ALL of the unapplied deletions.
  2. Delete the __pycache__ folder that's inside of the migrations folder.
  3. Edit the models as desired.
  4. Makemigrations and migrate.

If All Else Fails

If errors are still being encountered, it may be necessary to delete the database...

πŸ‘€ All existing data and users will be deleted.

  1. Delete the database in Neon.
  2. Recreate your database in Neon.
  3. Delete everything that's inside of the main_app/migrations folder (including the __pycache__ folder) EXCEPT for the __init__.py file.
  4. Makemigrations and migrate.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment