如何在Django模型中将枚举用作选择字段 [英] How to use enums as a choice field in django model

查看:855
本文介绍了如何在Django模型中将枚举用作选择字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型类,我希望两个字段成为一个选择字段,因此为了填充这些选择,我使用了下面列出的枚举

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 选择。 c $ c>。

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 ,如此处。这样,您不必自己构造选择元组。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆