How to Rollback Migration in Django: Simple Guide
To rollback a migration in Django, use the
python manage.py migrate app_name migration_name command, specifying the migration you want to revert to. This command undoes all migrations applied after the specified one, effectively rolling back your database schema.Syntax
The basic syntax to rollback a migration in Django is:
python manage.py migrate <app_name> <migration_name>
Here, app_name is the name of your Django app, and migration_name is the migration you want to rollback to. If you specify a migration that is earlier than the current state, Django will undo migrations applied after it.
bash
python manage.py migrate app_name migration_name
Example
This example shows how to rollback the last migration of an app named blog. Suppose the latest migration is 0003_auto, and you want to rollback to 0002_auto:
bash
python manage.py migrate blog 0002_autoOutput
Operations to perform:
- Unapply migration blog.0003_auto
Running migrations:
- blog: 0002_auto
Common Pitfalls
Common mistakes when rolling back migrations include:
- Not specifying the app name, which causes Django to rollback all apps to the given migration, often leading to errors.
- Trying to rollback to a migration that does not exist or is misspelled.
- Rolling back migrations that have data dependencies without handling data loss.
- Forgetting to run
makemigrationsafter manual model changes before migrating again.
Always check your migration history with python manage.py showmigrations before rolling back.
bash
Wrong: python manage.py migrate 0002_auto Right: python manage.py migrate blog 0002_auto
Quick Reference
| Command | Description |
|---|---|
| python manage.py showmigrations | List all migrations and their applied status |
| python manage.py migrate | Apply all unapplied migrations |
| python manage.py migrate app_name migration_name | Rollback or migrate app to specific migration |
| python manage.py migrate app_name zero | Rollback all migrations of the app |
Key Takeaways
Use
python manage.py migrate app_name migration_name to rollback migrations safely.Always specify the app name to avoid unintended rollbacks.
Check migration history with
showmigrations before rolling back.Rolling back can cause data loss; backup your database if needed.
Use
migrate app_name zero to rollback all migrations of an app.