简体   繁体   English

在Django中将CharField转换为Choice Field(PositiveSmallIntegerField)

[英]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" . 为了论证,所有的值都是"foo""bar"

I want to convert this to be a PositiveSmallIntegerField instead with the following set up: 我想将此转换为PositiveSmallIntegerField,而不是使用以下设置:

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? 有什么方法可以将旧的my_field CharField转换为PositiveSmallIntegerField并保留所有旧数据? 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? 或者我是否必须向模型添加新字段,通过对旧字段运行脚本来填充值,删除旧字段,然后将PositiveSmallIntegerField重命名为旧CharField的名称?

There are no Django model ChoiceField? 没有Django模型ChoiceField?

I think you can add 'choices' to your CharField without losing any data. 我认为您可以在CharField中添加“选择”而不会丢失任何数据。 See https://docs.djangoproject.com/en/1.9/ref/models/fields/#choices 请参阅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. 但是,如果要将字段类型更改为“PositiveIntegerField”,则必须执行多个步骤。

  1. Add a PositiveIntegerField to model w/ the choices 添加PositiveIntegerField以模拟选择
  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 有关Django迁移的文档: https//docs.djangoproject.com/en/1.9/ref/django-admin/#makemigrations

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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