Rollback migrations in Django, 2 ways
In Django, we don't have a direct command like migrate rollback to roll back migrations, which would be extremely useful in many situations.
We often create our models, generate the associated migrations using the makemigrations command, and then realize we made a mistake... and well, that's a huge problem.
Option 1: Revert all migrations for an app
For this case, I'll show you a couple of ways to do it. Again, there may be many implementations, but they all follow more or less the same path.
A very common option is to run the following command:
python manage.py migrate nombre_app zero
For example, if your app is called blog, it would be:
python manage.py migrate blog zero
What does this mean?
All migrations for the blog application, which is supposedly the one with the problem and needs to be fixed, will be reverted.
After that, you'll need to make corrections to both your model and, possibly, the generated migration files.
For example, if you forgot to add the description field, you can do so directly in the model, or you can also manually modify the migration by duplicating and adjusting an existing block, if you prefer.
Option 2: Roll back to a specific migration
Another option is to specify exactly which migration you want to return to.
For example:
python manage.py migrate blog 0002
This means you want to return to migration 0002.
Remember that migrations grow each time you make changes to your models. For example:
- 0001_initial.py
- 0002_add_description.py
- 0003_add_subscribers.py
And so on, depending on the changes you make to the blog app.
This method is useful if, for example, you later add a migration for subscribers or another table, and you need to revert only to a specific point without deleting everything before.
Which one to use?
In summary:
- If you want to delete all migrations for an app (for example, because you're starting from scratch or the error is from the beginning), you can use the zero option.
- If you want to revert only a specific migration without deleting everything, you can use the exact migration number as in the second method.
This second command would be the closest to the concept of a rollback, as it allows you to return to a previous, specific state.
It's not as automatic as a rollback, but it essentially accomplishes the same goal: reverting a migration so you can correct something that went wrong.
So, if you only have one migration or the error is in the first one, the zero option is perfect.
But if you need a little more control, you can specify the exact migration you want to revert to.
I agree to receive announcements of interest about this Blog.
I'll show you a couple of ways to revert migrations in Django when there's no rollback command in the framework.
- Andrés Cruz