Bigbob556677
Bigbob556677

Reputation: 2158

Migrate From An IntegerField With Choices To A CharField

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

Answers (3)

bryan60
bryan60

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

AKX
AKX

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:

  • rename gender to gender_integer (or similar); make a migration out of that
  • add the new gender field; make a migration out of that
  • create a data migration to map gender_integer's content to gender (see the link above)
  • remove gender_integer; make a migration out of that.

Upvotes: 4

kamilyrb
kamilyrb

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

Related Questions