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 migrations has been unapplied, it's safe to:
- Delete ALL of the unapplied deletions.
- Delete the
__pycache__
folder that's inside of themigrations
folder. - Edit the models as desired.
- Makemigrations and migrate.
If errors are still being encountered, it may be necessary to delete the database...
π All existing data and users will be deleted.
- Delete the database in Neon.
- Recreate your database in Neon.
- Delete everything that's inside of the
main_app/migrations
folder (including the__pycache__
folder) EXCEPT for the__init__.py
file. - Makemigrations and migrate.