Adding South Migrations to Django

Database migrations: Django doesn’t have them built in, but that doesn’t mean we’re stuck in a multi-developer, multi-database, ALTER TABLE purgatory. In fact there are a couple of options, and the one I’ve looked at is South.

Getting started is easy: by the end of this post you’ll have installed South, have a couple of migrations, and be able to add and remove columns from your tables. What you won’t learn is how to write custom migrations or migrate data.

Geese migrating south by nordicshutter

Geese migrating south by nordicshutter.

Installing South

The First Migration

Assuming you’re adding South to an existing project, the first migration is super simple:

./manage.py startmigration [app name] --initial

This will generate the first migration for your [app name] (where [app name] is the last part of an app name in your INSTALLED_APPS setting). The syncdb we did above should have installed the South tables, but because we have existing models, we need to fake the migration:

./manage.py migrate [app name] --fake

The Next Migrations

Once you’ve altered your models you’ll want to create more migrations, this is done with the following command:

./manage.py startmigration [app name] [migration name] --auto

And then we’re ready to migrate the database:

./manage.py migrate [app name]

By this point you’ve probably noticed that in your app folder there’s now a migrations folder with sequentially named files. To migrate to a specific version, we use:

./manage.py migrate [app name] 0002

If the current state of the database is ahead of the specified migration, the above command will migrate backwards (probably removing columns), otherwise it will migrate forwards (adding columns).

Next Steps

What I’ve described is only dipping toes into the South water. To find out more, checkout the excellent South Tutorial, and the South Command Reference.

Posted on Thursday 30th April, 2009.

The short URL for this post is: http://sneeu.com/s/pQ