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? Do I need to do a Database migration (I'm using 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是否使用数据库约束来强制执行选择?我是否需要进行数据库迁移(我正在使用South)?或者Django只是在Python代码中强制执行选择限制,我所要做的就是更改代码并重新启动?
Thanks!
谢谢!
2 个解决方案
#1
11
Django doesn't enforce choices on a database level, it only uses them for the presentation of the widgets and in validation. If you want them a bit more 'dynamic', for example to have different ones on different servers you could define them via settings.py
:
Django不强制在数据库级别上进行选择,它只使用它们来呈现小部件和验证。如果你想要它们更“动态”,例如在不同的服务器上有不同的,你可以通过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中定义不同的选项(无需任何数据库迁移!)。
#2
1
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.
不,它不会强制执行选择/您不需要触摸您的数据库。
#1
11
Django doesn't enforce choices on a database level, it only uses them for the presentation of the widgets and in validation. If you want them a bit more 'dynamic', for example to have different ones on different servers you could define them via settings.py
:
Django不强制在数据库级别上进行选择,它只使用它们来呈现小部件和验证。如果你想要它们更“动态”,例如在不同的服务器上有不同的,你可以通过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中定义不同的选项(无需任何数据库迁移!)。
#2
1
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.
不,它不会强制执行选择/您不需要触摸您的数据库。