How to Undo Django Migrations

created:

updated:

tags: django database migration

Recently at work, I was adding a new model in Django, and my commit was based on my coworker’s commit that also added a new model. At some point, I had messed up my local database migration process and I encountered an error like this:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'.

Something similar to the above (I copied the error message from the Internet).

At this point, I was wondering if I should run the command to drop my current local database and rebuild it. However, I didn’t want to do it since that will remove all my existing data.

Option 1: Reverse Django’s migrations

While browsing Django’s documentation on migrations, I learned that I can undo database migration for a specific migration.

Under ‘Reversing migrations’ section, it describes how we can reverse migrations.

We can use python manage.py migrate <table_name> <previous migration number to reverse to> command and pass the name of the database app label and the number of the specific migration that you want to go back to.

$ python manage.py migrate books 0002
Operations to perform:
  Target specific migration: 0002_auto, from books
Running migrations:
  Rendering model states... DONE
  Unapplying books.0003_auto... OK

The above example shows how it reversed books database to the migration #002.

Option 2: Drop a specific database table