In Django I have a model with the following IntegerField.
GENDER_CHOICES = (
(0, 'Male'),
(1, 'Female'),
)
gender = models.IntegerField(choices=GENDER_CHOICES)
I would like to altar this model to become a CharField using the choices.
GENDER_CHOICES = (
("MALE", 'Male'),
("FEMALE", 'Female'),
("NA", 'Id Rather Not Say'),
)
gender = models.CharField(choices=GENDER_CHOICES, max_length=10)
If I were to do this by running makemigrations
and migrate
I would lose the existing data in the database.
How would I make this (and similar) migrations without losing the existing data in the database?
Ideally I would do this in the migration itself that way it will run on the production server the second we use the migrate
command.
You'll need a data migration (as I recently outlined in this answer: How to modify a models who's already migrated in Database? ), but the steps are:
gender
to gender_integer
(or similar); make a migration out of thatgender
field; make a migration out of thatgender_integer
's content to gender
(see the link above)gender_integer
; make a migration out of that.Firstly, you can store your old field and add new field your model with new choices. After that you can run standalone code and map your old data to new field.
Migration 1: make a char field like gender_tmp, migrate all the data to it
Migration 2: remove gender and rename gender_tmp to gender
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.