简体   繁体   中英

Django migrations - change model from Int to CharField and pre-populate from choice option

In a model, I have an IntegerField that is mapped to a CHOICES tuple. The requirements for that field have changed to the point that updating the options in that tuple will require too frequent maintenance, so I've decided to alter it to a CharField

Is there a way I can do this inside the migrations, or would it be better to create a new column, update with the appropriate value and delete old column?

You've changed your Schema so you'll definitely need a Schema migration and Django will do that for you, with the makemigrations command.

But since you're also changing the type of a column, in which is filled with integers and now should be cast to characters, Django won't do that automatically for you and you need to write Data migrations .

In my experience, it's better to generate multiple migrations; one that creates a new CharField and then write to this new column via RunPython. Then, run a second migration that removes the original IntegerField and renames the new CharField column as your original column. (I guess it's what you yourself suggested)

To make it more clear, you need 3 migrations.

  1. for Schema migration - adding a new field.
  2. for Data migration - You can use the link below which is perfect example for data migration.
  3. for Schema migration - deleting the old field.

Here is the example I've followed before doing my first data migrations.

Data Migration Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM