Proper way to rename FK in django using south (postgress DB backend)
There is a problem in renaming FK keys using south in django when you are using postgres.
I tried this method:
The problem raised when I tried to create new field named 'old_field_name' (pointing to model 'auth.User') and it said that field already exists. The problem raised because foreign-key constrants remained for 'old_field_name' and they should be recreated.
Proper way:
Notes: ForeignKey should point to model that original 'old_field_name' pointed to. 'null=True'
I tried this method:
old_field_name_id pointed to custom user model.db.rename_column('app_label', 'old_field_name_id', 'temp_old_field_name_id')
The problem raised when I tried to create new field named 'old_field_name' (pointing to model 'auth.User') and it said that field already exists. The problem raised because foreign-key constrants remained for 'old_field_name' and they should be recreated.
Proper way:
class Migration(SchemaMigration): def forwards(self, orm): from django.conf import settings table_name = 'users_address' old_field_name = 'user_id' new_field_name = 'old_user_id' if settings.DATABASES['default']['ENGINE'].endswith('psycopg2') or settings.DATABASES['default']['ENGINE'].endswith('postgis'): db.drop_foreign_key(table_name, old_field_name) db.delete_index(table_name, [old_field_name]) db.rename_column(table_name, old_field_name, new_field_name) if settings.DATABASES['default']['ENGINE'].endswith('psycopg2') or settings.DATABASES['default']['ENGINE'].endswith('postgis'): db.alter_column(table_name, new_field_name, models.ForeignKey(null=True, to=orm['users.User'])) db.create_index(table_name, [new_field_name]) # you can easily find out how to write backward mibration yourself
Notes: ForeignKey should point to model that original 'old_field_name' pointed to. 'null=True'