Getting Started with South (Django Database Migrations)

southIf you have worked on a project in Django, you have undoubtedly discovered that ‘syncdb’ is great at turning your ‘models.py’ files into real database tables but not so great at taking your modified models and altering your database with the new definitions. In fact, the Django documentation is pretty clear about this: “Syncdb will not alter existing tables”.

South is a Django project which solves this problem by providing “consistent, easy-to-use, database-agnostic migrations for Django applications.” Below are the most basic steps for getting South up and running in your project.

INSTALLING SOUTH

  1. pip install south     (if you’re lucky, otherwise RTFM)
  2. add ‘south’ to your project’s INSTALLED_APPS
  3. run ‘syncdb’     (before you create your own models)
  4. note: this is the last time you’ll run ‘syncdb’

YOUR FIRST MIGRATION

  1. create a new app and create your initial ‘models.py’ file for it
  2. add your app to your project’s INSTALLED_APPS
  3. run ‘python manage.py schemamigration myapp –initial’      (creates your initial migration, note: those are two dashes hyphens before initial)
  4. run ‘python manage.py migrate myapp’     (uses this initial migration to create your app’s DB tables)

MIGRATING A CHANGED MODEL

  1. modify your app’s models.py file    (e.g., add a new column somewhere)
  2. run ‘python manage.py schemamigration myapp –auto’    (creates a new migration, note: those are two dashes hyphens before auto)
  3. run ‘python manage.py migrate myapp’    (applies this new migration)

That’s it, the very bare bones steps to getting up and running with South. Obviously you’ll either need to run these commands in the same directory as ‘manage.py’ or change the commands to point to it.

One last thing…

AN OPTIONAL SHELL FUNCTION TO HELP OUT

  1. vi ~/.bash_aliases    (there’s probably a better home for this, but this is where I put mine)
  2. add:
    function mig() {
        python manage.py schemamigration "$@" --auto;
        python manage.py migrate "$@";
    }
  3. source .bash_aliases    (to activate the changes)
  4. now you can run ‘mig myapp’ whenever you change the model for ‘myapp’

If you want to be able to run this shell function anywhere, put the full path to your project’s ‘manage.py’ file in the function body. Otherwise, you’ll have to run it in the same directory as the relevant ‘manage.py’.

For South’s more advanced goodness, check out the documentation.

South 0.7
Django 1.2.1
Python 2.5.2.