How to revert migrations in Django?

How to revert migrations in Django?

Sometimes we run a migration that make changes in our database, but we want to revert it and delete the migration, without creating a new migration.

Gaurav Sharma's photo
Gaurav Sharma
·May 13, 2022·

2 min read

Subscribe to our newsletter and never miss any upcoming articles

Play this article

Introduction:

Sometimes we run a migration that make changes in our database, but we want to revert it and delete the migration, without creating a new migration.

Well, in that case, there is a small trick that you can use to revert your migration safely.

Assumption for this Blog:

Before we get into the actual steps, let’s assume a few things to understand the example better:

  • Our Project name is myproject.
  • The App name is myapp.
  • Our latest two latest migrations are:
    • 0003_latest_migration
    • 0002_previous_migration
  • Migration to revert is 0003_latest_migration

Steps to revert the migrations by its number:

In Django, Migrations can be reversed with migrate command by passing the number of the previous migration.

To revert a migration 003, we have to run this command:

python manage.py migrate myapp 0002

The above command will remove the applied changes of 0003_latest_migration and revert it back to 0002_previous_migration. Output will be something like this:

Operations to perform:
  Target specific migration: 0002_previous_migration, from myapp
Running migrations:
  Rendering model states... DONE
  Unapplying myapp.0003_latest_migration... OK

Steps to revert all the migrations:

In Django, If you want to reverse all migrations applied for an app, use the name zero with the migrate command.

python manage.py migrate myapp zero

The above command will remove the all the applied changes of the Django app myapp, Output will be something like this:

Operations to perform:
  Unapply all migrations: myapp
Running migrations:
  Rendering model states... DONE
  Unapplying myapp.0002_previous_migration... OK
  Unapplying myapp.0001_initial... OK

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.

Did you find this article valuable?

Support Dev.Junction by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this