Django migrations can be unapplied to a database in the reverse order that they were applied using the following commands...
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
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
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
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
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.