Reputation: 2158
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.
Upvotes: 1
Views: 374
Reputation: 29335
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
Upvotes: 0
Reputation: 168913
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.Upvotes: 4
Reputation: 2627
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.
Upvotes: 0