Migration Issues? Damage Control for your Django Project

Messed up a migration? Here are some tips to get your project's database back to stability.

Go Back

Preface

Eventually at some point during development you'll come across an issue migrating changes to your database. At this point you begin freaking out because now the stability of your back-end architecture might be compromised. Keep calm and try these steps first.

 

Reverting to a Previous Migration

Before trying anything with your migrations, first we need to take a look at the available migrations in your app to see which one we want to revert. Try the following to get a list of your app's migrations:

./manage.py showmigrations my_app

Now lets try reverting to a previous migration which is the first and simplest step to approaching this problem. Let's say in your django app called my_app, you have a migration folder which contains:

  • 0100_prev_migration
  • 0050_old_migration

 You want to revert to the migration 0050_old_migration, try the following:

./manage.py migrate my_app 0050_old_migration

You can now delete the 0100_prev_migration file at this point.

 

Reverting All Migrations for an App

Now the problem appears to be with many of your migrations. So let's go further and reverse all the migrations made to my_app:

./manage.py migrate my_app zero

 

Warnings

  • Do not delete the migrations folder of an app, especially the __init__.py file in the migration folder.
  • Remember that all your migrations are not just stored in migration files, but in the migrations table of your database as well. So if you delete your migration files, running the migrate operation won't do anything.
  • If you need to go nuclear and completely clear out a migration and destroy your database, delete all the necassary migration files except for __init__.py. Delete the necassary rows in the django_migrations where app is your app's name. Drop all related tables of your app, then remake your migrations. Do this series of steps if you have exhausted other options, and your okay with getting rid of your data.