开发者

How do I change the choices in a Django model?

I have a Django model that uses the choices attribute.

COLOR_CHOICES = (
    ('R', 'Red'),
    ('B', 'Blue'),
)
class Toy(models.Model):
    color = models.CharFiel开发者_JAVA百科d(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?

Thanks!


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:

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!).


The field is models.CharField so the database will treat it like any other models.CharField set up in django :)

No, it doesn't enforce choices / you don't need to touch your DB.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜