How to revert migrations in Django?

How to revert migrations in Django?

A guide on reverting migrations in Django

Note: If you are looking for a Full Stack Developer (Django+React), then connect with me on LinkedIn or contact me through my portfolio.

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!