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

发布于 2024-10-08 20:23:34 字数 651 浏览 0 评论 0原文

我有一个使用 choices 的 Django 模型属性

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

我的代码正在生产中,现在我想添加其他选择。

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

我该怎么做呢? Django 是否使用数据库约束来强制选择?我是否需要进行数据库迁移(我使用的是 South)?或者 Django 只是在 Python 代码中强制执行选择限制,而我所要做的就是更改代码并重新启动?

谢谢!

I have a Django model that uses the choices attribute.

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?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

注定孤独终老 2024-10-15 20:23:34

Django 不会在数据库级别强制执行选择,它仅将它们用于小部件的呈现和验证。如果您希望它们更加“动态”,例如在不同的服务器上有不同的,您可以通过settings.py定义它们:

from django.conf import settings

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

然后您可以在settings.py中定义不同的选择 (无需任何数据库迁移!)。

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

眼泪都笑了 2024-10-15 20:23:34

该字段是 models.CharField 因此数据库会像 django 中设置的任何其他 models.CharField 一样对待它:)

不,它不会强制选择/你不强制执行选择不需要接触你的数据库。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文