close

How to use enums as a choice field in django model

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to use enums as a choice field in django model in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to use enums as a choice field in django model ?

  1. How to use enums as a choice field in django model

    By the way Djanog also supports the Python 3's auto() as the Enum value. You can use the following helperclass to make your life easier.

  2. use enums as a choice field in django model

    By the way Djanog also supports the Python 3's auto() as the Enum value. You can use the following helperclass to make your life easier.

Method 1

For Django 2.x and lower:

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"

Note there are no commas! This allows you later in your code to refer to TransactionStatus.ERROR or TransactionStatus.PENDING.

The rest of your code is correct. You get the choices by creating tuples of option.nameoption.value.

UPDATE: For Django 3.x and higher, use the built-in types TextChoicesIntegerChoices and Choices as described here. That way you don’t have to construct the choices tuple yourself.

Method 2

By the way Djanog also supports the Python 3’s auto() as the Enum value. You can use the following helperclass to make your life easier.

from django.db.models.enums import TextChoices

class AutoEnumChoices(TextChoices):
    def _generate_next_value_(name, start, count, last_values):  # @NoSelf
        return name.lower()
    
    @property
    def choices(cls):  # @NoSelf
        empty = [(None, cls.__empty__)] if hasattr(cls, '__empty__') else []
        return empty + [(member.value, member.label) for member in cls]

Then use it in your choices definition:

class TransferBasicStatus(AutoEnumChoices):
    NONE = auto()
    WAITING = auto()
    PENDING = auto()
    PROGRESS = auto()
    SUCCESS = auto()
    DECLINED = auto()
    ENDED =  'ended', _('Ended - The transfer has ended with mixed states')

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read