我有一个模型类,我希望其中的两个字段成为一个选择字段,因此为了填充这些选择,我正在使用下面列出的枚举
#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)
但是,当我尝试通过管理员访问此模型时,出现以下错误:
Django Version: 1.11
Exception Type: ValueError
Exception Value:
too many values to unpack (expected 2)
我关注了两篇描述如何使用枚举的文章:
- 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/
原文由 Paras 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的代码中的问题是
INITIATED = "INITIATED",
INITIATED
选项和其他选项之后的逗号。当我们在任何字符串后添加逗号时,它将成为一个元组。请参阅下面的示例#models.py
#enums.py
对于 django > 3.0 https://docs.djangoproject.com/en/4.0/ref/models/fields/#field-choices-enum-types