简体   繁体   English

如何更改Django模型中的选项?

[英]How do I change the choices in a Django model?

I have a Django model that uses the choices attribute . 我有一个使用choices 属性的Django模型。

COLOR_CHOICES = (
    ('R', 'Red'),
    ('B', 'Blue'),
)
class Toy(models.Model):
    color = models.CharField(max_length=1, choices=COLOR_CHOICES)

My code is in production and now I'd like to add additional choices. 我的代码正在生产中,现在我想添加其他选择。

COLOR_CHOICES = (
        ('R', 'Red'),
        ('B', 'Blue'),
        ('G', 'Green'),
 )

How do I go about doing this? 我该怎么做呢? Does Django use Database constraints to enforce choices? Django是否使用数据库约束来强制执行选择? Do I need to do a Database migration (I'm using South )? 我是否需要进行数据库迁移(我正在使用South )? Or does Django just enforce the choices restriction in Python code and all I have to do is change the code and restart? 或者Django只是强制执行Python代码中的选择限制,我所要做的就是更改代码并重新启动?

Thanks! 谢谢!

Django doesn't enforce choices on a database level, it only uses them for the presentation of the widgets and in validation. Django不强制在数据库级别上进行选择,它只使用它们来呈现小部件和验证。 If you want them a bit more 'dynamic', for example to have different ones on different servers you could define them via settings.py : 如果你想要它们更“动态”,例如在不同的服务器上有不同的,你可以通过settings.py定义它们:

from django.conf import settings

COLOR_CHOICES = getattr(settings, 'COLOR_CHOICES',(
        ('R', 'Red'),
        ('B', 'Blue'),
        ('G', 'Green'),
 ))

Then you could define different choices in your settings.py (no need for any database migration!). 然后,您可以在settings.py定义不同的选项(无需任何数据库迁移!)。

The field is models.CharField so the database will treat it like any other models.CharField set up in django :) 该字段是models.CharField所以数据库将像任何其他models.CharField设置在django :)

No, it doesn't enforce choices / you don't need to touch your DB. 不,它不会强制执行选择/您不需要触摸您的数据库。

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

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