views:

87

answers:

1

I have a django project with a database table that already contains data. I'd like to change the field name without losing any of the data in that column. My original plan was to simply change the model field name in a way that would not actually alter the name of the db table (using the db_column column parameter):

The original model:

class Foo(models.Model):
  orig_name = models.CharField(max_length=50)

The new model:

class Foo(models.Model):
  name = models.CharField(max_length=50, db_column='orig_name')

But, running South's schemamigration --auto produces a migration script that deletes the original column, orig_name, and adds a new column, name, which would have the unwanted side effect of deleting the data in that column. (I'm also confused as to why South wants to change the name of the column in the db, since my understanding of db_column was that it enables a change to the model field name without changing the name of the database table column).

If I can't get away with changing the model field without changing the db field, I guess I could do a more straight forward name change like so:

The original model:

class Foo(models.Model):
  orig_name = models.CharField(max_length=50)

The new model:

class Foo(models.Model):
  name = models.CharField(max_length=50)

Regardless of which strategy I end up using (I would prefer the first, but would find the second acceptable), my primary concern is ensuring that I don't lose the data that is already in that column.

Does this require a multi-step process? (such as 1. adding a column, 2. migrating the data from the old column to the new column, and 3. removing the original column) Or can I alter the migration script with something like db.alter_column?

What is the best way to preserve the data in that column while changing the column's name?

+1  A: 

It is quite easy to fix. But you will have to modify the migration yourself.

Instead of dropping and adding the column, use db.rename_column. You can simply modify the migration created by schemamigration --auto

WoLpH
nice! i thought there would be a simple solution.So if I add the following to forwards:db.rename_column('myapp.foo', 'orig_name', 'name')and the following to backwards:db.rename_column('myapp.foo', 'name', 'orig_name')should these changes be added to a migration script that includes the change to the model definition? or should I not manually change the model definition before creating the migration script? (if my question is unclear, let me know, and I'll explain it differently)
sfletche
nevermind, that was dumb question. i'll change the model definition first, then create an --empty migration script, and alter the forwards and backwards methods to include the rename_column data I included above.Thanks!
sfletche