[Python] How can one use enums as a choice field in a Django model?

Discussão em 'Python' iniciado por Stack, Julho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have a model class in which I want two fields to be choice fields, so to populate those choices I am using an enum as listed below:

    #models.py
    class Transaction(models.Model):
    transaction_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 the Django 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:


    Continue reading...

Compartilhe esta Página