简体   繁体   中英

Convert CharField to Choice Field (PositiveSmallIntegerField) in Django

My current model is set up as follows:

Class MyClass(models.Model):
    my_field = models.CharField(max_length=100,...)

All of the values are either, for sake of argument, "foo" or "bar" .

I want to convert this to be a PositiveSmallIntegerField instead with the following set up:

Class MyClass(models.Model):
    FOO = 0
    BAR = 1
    FOO_BAR_CHOICES = (
        (FOO, 'foo')
        (BAR, 'bar')
    )
    my_field = models.PositiveSmallIntegerField(choices=FOO_BAR_CHOICES,...)

Is there any way that I can convert the old my_field CharField to be a PositiveSmallIntegerField and keep all of my old data? Or do I have to add a new field to my models, populate the values by running a script against the old field, delete the old field, then rename my PositiveSmallIntegerField to the name of the old CharField?

There are no Django model ChoiceField?

I think you can add 'choices' to your CharField without losing any data. See https://docs.djangoproject.com/en/1.9/ref/models/fields/#choices

However if you want to change the field type to 'PositiveIntegerField'.. you'll have to do in multiple steps.

  1. Add a PositiveIntegerField to model w/ the choices
  2. Write a data migration.. to copy data from the old field to new field
  3. Delete old field.

Docs on Django migrations: https://docs.djangoproject.com/en/1.9/ref/django-admin/#makemigrations

Hope this helps.

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