在 Django 模型中指定一个 mySQL ENUM

2021-12-19 00:00:00 python django django-models enums mysql

如何在 Django 模型中指定和使用 ENUM?

How do I go about specifying and using an ENUM in a Django model?

推荐答案

来自 Django 文档:

MAYBECHOICE = (
    ('y', 'Yes'),
    ('n', 'No'),
    ('u', 'Unknown'),
)

然后在模型中定义一个字符域:

And you define a charfield in your model :

married = models.CharField(max_length=1, choices=MAYBECHOICE)

如果你不喜欢有字母,你可以对整数字段做同样的事情在您的数据库中.

You can do the same with integer fields if you don't like to have letters in your db.

在这种情况下,重写您的选择:

In that case, rewrite your choices:

MAYBECHOICE = (
    (0, 'Yes'),
    (1, 'No'),
    (2, 'Unknown'),
)

相关文章