3

I need to rename a foreign key in my django model using south migrations. I thought I was in luck when I found this thread How to rename a foreignkey field with South? However, all the methods described there fail, with various errors. Does someone actually know the proper way to do this?

I want to rename SomeModel.registered_to = models.ForeignKey( User ) to SomeModel.owner = models.ForeignKey( User ) and keep the relation between User and owner Any help would be appreciated!

Community
  • 1
  • 1
john-charles
  • 1,417
  • 4
  • 17
  • 30

1 Answers1

3

Change the field name and run python manage.py schemamigration --auto yourapp. South will add code to drop the column and add a new one. Letting South generate the migration ensures that the ORM is frozen properly, so all you need to do is just change the actual migration to rename instead of drop and add. Just remove those lines from the forwards and backwards migration to and replace them with:

def forwards(self, orm):
    db.rename_column('yourapp_yourmodel', 'registered_to_id', 'owner_id')

def backwards(self, orm):
    db.rename_column('yourapp_yourmodel', 'owner_id', 'registered_to_id')

Save, and then migrate your app.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • That technique was mentioned in the thread I linked to above, and I have tried it. It appears to work, does not throw any exceptions. But after it completes any attempt to access `SomeModel.owner` will raise `DoesNotExist` – john-charles Mar 05 '12 at 16:39
  • 3
    In Postgres, this seems to work for changing the foreign key name. The constraint name stays the same though... does that matter? – Nils Jun 01 '12 at 05:59