Django model - changing options in a select box and migrating

I need to change the name of the parameters in the model state field which should become

   STATUS = Choices(
    ('option_A', 'Option A'),
    ('option_B', 'Option B'),
   )

      

Before this change, I had the same options, but the names are different. Now I've changed everything in the project to respect the new names, but the problem is updating the database to reflect these new names. I am using South to migrate data, and as far as I understand, it is quite simple to write an automatic migration if you need to add or remove a column in the database, but I cannot find a way to do this update for my existing column.

I am using Django 1.6.

+3


source to share


3 answers


You can write a quick script to make changes. Something like that:

>>Model.objects.filter(status = "some_old_value").update(status = "new_value")

      

Where "status" is the name of the field. You can repeat the above step to change any old values ​​to new values ​​in the same model.



Update () is much faster and doesn't take long to run on a moderate sized database https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once

Also, since this will be a one-off script, speed shouldn't be a major issue.

Hope it helps

+4


source


What you are looking for is datamigration.

$ python manage.py datamigration your_app_label

      

This will create a new empty migration in your migration folders. You need to manually create the methods forwards

and backwards

to change the data as you want:

def forwards(self, orm):
    orm.MyModel.objects.filter(status='old_option_A').update(status='option_A')
    ...

def backwards(self, orm):
    # reverse of forwards, or raise an error to prevent backwards migrations

      



You will need to use orm.MyModel

instead of directly importing a model for this.

Then just run the migration:

$ python manage.py migrate your_app_label

      

Make sure to specify both the porting and the parameter change in the same commit in your source control so that they always stay in sync (until people remember upgrading to a new version).

+5


source


After changing the fields, you should run:

$ python manage.py makemigrations your_app_label
$ python manage.py migrate 

      

(This work for Django 1.7 where south is included in the Django package)

In case of Django 1.6:

  • pip install South

  • -python manage.py schemamigration your_app_name --initial

  • -python manage.py migrate your_app_name

  • make changes to your model.

  • manage.py schemamigration your_app_name --auto (migrations via change will be added)

  • python manage.py migrate your_app_name

Also here is the first step towards a southern translation.

0


source







All Articles