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')
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.

2 Responses to “Add foreign key constraints in South migration”

  • Jonathan Hartley Says:

    Hey. I have a column with three foreign key constraints on it. One of them is faulty (a leftover constraint from when a referenced model was in a different Django app. South created the new constraint when we moved the referenced model, but didn’t delete this one)

    Can I add a new migration to delete this constraint without deleting and having to re-create the others?

  • Béres Botond Says:

    Looking at how delete_foreign_key is implemented in South’s source code, you should be able to do something like:

    sql = db.delete_foreign_key_sql % {
                    "table": "table_name",
                    "constraint": "constraint name",

Leave a Reply