Django migrations walk-through

Hi all,

I wrote up a post on Django’s migrations. I cover a high level overview of how they work, how you can get into trouble with them and how to recover (beyond creating a new database). Let me know what you think!

It is a bit long, so here’s the TLDR from the post.

Toolkit:

  • manage.py makemigrations: Creates the migration files
  • manage.py migrate: Runs the migrations (changes the database)
  • manage.py showmigrations --verbosity 2: Tells you what migrations have been applied and when
  • manage.py sqlmigrate <app> <migration>: Tells you what SQL will run for a migration
  • manage.py dbshell: Opens up a database SQL shell (we used sqlite3 directly)

Strategies:

  • Make a backup of your database before changing it
  • Commit your migrations
  • Before changing/deleting a migration file, make sure it’s unapplied in every environment first
  • When migrate fails, investigate the current database schema and the generated SQL from the migration
  • Use SQL diffing tools to compare the schema with a known good database
7 Likes