May 4 2010

Add foreign key constraints in South migration

Béres Botond

Recently I needed to do something specific in a migration. I wanted to add foreign key constraints, but without any other change to models. Basically there was no change to “frozen” models, those were already correct, but somehow the database itself was missing a constraint (legacy database – app has only been converted to South fairly recently). I wanted to avoid raw SQL if possible, but initially looking at the docs I saw a db API method for deleting FK constraint but not for adding one. But after a quick look at the source it turns out there is a simple method:

def forwards(self, orm):
        sql = db.foreign_key_sql('from_table', 'from_field', 'to_table', 'to_field')
        db.execute(sql)
 
def backwards(self, orm):
        db.delete_foreign_key('from_table', 'from_field')

By the way if you develop applications with Django and are not using South yet (or at least some other migration tool), you better check it out, as it is currently the most up to date and stable migration app for it.