如何在 Django 模型中使用枚举作为选择字段 [英] How to use enums as a choice field in django model
问题描述
我有一个模型类,我希望其中的两个字段作为选择字段,因此为了填充这些选择,我使用了下面列出的枚举
I have a model class of which I want two fields to be a choice fields, so to populate those choices I am using an enum as listed below
#models.py
class Transaction(models.Model):
trasaction_status = models.CharField(max_length=255, choices=TransactionStatus.choices())
transaction_type = models.CharField(max_length=255, choices=TransactionType.choices())
#enums.py
class TransactionType(Enum):
IN = "IN",
OUT = "OUT"
@classmethod
def choices(cls):
print(tuple((i.name, i.value) for i in cls))
return tuple((i.name, i.value) for i in cls)
class TransactionStatus(Enum):
INITIATED = "INITIATED",
PENDING = "PENDING",
COMPLETED = "COMPLETED",
FAILED = "FAILED"
ERROR = "ERROR"
@classmethod
def choices(cls):
print(tuple((i.name, i.value) for i in cls))
return tuple((i.name, i.value) for i in cls)
但是,当我尝试通过管理员访问此模型时,出现以下错误:
However, when I am trying to access this model through admin I am getting the following error :
Django Version: 1.11
Exception Type: ValueError
Exception Value:
too many values to unpack (expected 2)
我关注了两篇描述如何使用枚举的文章:
I followed two articles that described how to use enums:
- https://hackernoon.com/using-enum-as-model-field-choice-in-django-92d8b97aaa63
- https://blog.richard.do/2014/02/18/how-to-use-enums-for-django-field-choices/
推荐答案
对于 Django 2.x 及更低版本:
For Django 2.x and lower:
您可以通过设置各种选项来定义 Enum
这里:
You define an Enum
by setting the various options as documented here:
class TransactionStatus(Enum):
INITIATED = "INITIATED"
PENDING = "PENDING"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
ERROR = "ERROR"
注意没有逗号!这允许您稍后在代码中引用 TransactionStatus.ERROR
或 TransactionStatus.PENDING
.
Note there are no commas! This allows you later in your code to refer to TransactionStatus.ERROR
or TransactionStatus.PENDING
.
您的其余代码是正确的.您可以通过创建 option.name
、option.value
的元组来获得 choices
.
The rest of your code is correct. You get the choices
by creating tuples of option.name
, option.value
.
更新:对于 Django 3.x 及更高版本,使用内置类型 TextChoices
、IntegerChoices
和 Choices代码> 如此处所述.这样您就不必自己构建
choices
元组.
UPDATE: For Django 3.x and higher, use the built-in types TextChoices
, IntegerChoices
and Choices
as described here. That way you don't have to construct the choices
tuple yourself.
这篇关于如何在 Django 模型中使用枚举作为选择字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!