Python Django get enum choices

In this Python Django Tutorial, we will understand Python Django get enum choices. And we’ll also see different examples related to this. These are the following topics that we are going to discuss in this tutorial.

  • What is Enum
  • Why use Enum
  • When to use Enum
  • Python Django get enum choices
  • Python Django text enum choices
  • Python Django integer enum choices

What is Enum

In this section, we’ll learn what is an Enum.

Enum stands for Enumeration. Enumeration is a collection of symbolic names that are linked to distinct constant values.

Our Enum will be defined as a subclass of enum in the standard Python library. The following is the syntax to import enum.

# Import Library

from enum import Enum

# Create enum using class

class class_name(Enum):
    # define.....
     ......

Read: Python Django group by

Why use Enum

In this section, we’ll learn the uses of Enumeration.

  • We may use Python’s built-in Enum class to build unambiguous, reusable constants that can be used not only for models but also for other purposes.
  • To distinguish one value from another within a bunch of values.
  • Enums are best used to represent an immutable set of values.
  • Bascially, Enums are used when we know all the possible values at the time of compilation.

When to use Enum

In this section, we’ll learn when to use Enum.

  • Utilize it anytime in your code where you have a canonical source of enumerated data and wish to use the canonical name instead of arbitrary data.
  • Enumeration is useful for defining a set of immutable, connected constant values that may or may not have semantic significance.
  • Within a given process, to show error-status values.
  • Within a defined process, to show status value.

Read: Django for loop

Python Django get enum choices

In Django, to define choices for a Field in the Model we use Enumeration. There are two ways to store choices using enum classes.

  • Storing choices as text
  • Storing choices as integer

Storing choices as text

Storing choices as text means using characters as a symbol. Let’s see a small example to clear our understanding.

Example: Sunday as Sun, Monday as Mon, Tuesday as Tue, etc.

Storing choices as integer

Storing choice as integer means using numerical values as a symbol. Let’s look at a simple example to help us better.

Example: January as 1, February as 2, March as 3, etc.

Read: Python Django filter

Python Django text enum choices

In this section, we’ll learn how we can store choices as a text field in Django. Let’s see different examples related to this.

Example #1

In this example, we’ll take a field to identify the status of the post. We will use the given choices of status as Draft, Published, Scheduled, and Trash.

The following steps are being done to execute this example:

First, define the class for the choice:

# Import Library

from enum import Enum

# Create subclass of list

class BlogStatus(Enum):   
    P = "Published"
    D = "Draft"
    S = "Scheduled"
    T = "Trash"

Here, we create the subclass of the choice in the models.py file of the home app directory with the name BlogStatus.

Next, create the model:

# Import Library

from django.db import models

# Create Model

class Blog(models.Model):
    title = models.CharField(max_length=255)
    language = models.CharField(max_length=100)
    status = models.CharField(max_length=2, choices=[(tag, tag.value) for tag in BlogStatus])

Here, we create a model with the name Blog in the model.py file of the app. And in this model, we define the title, language, and status fields. We use the above define BlogStatus enum class in the status field of the model.

Then, define the admin part to view the table in the admin panel.

from django.contrib import admin
from .models import Blog

class AdminBlog(admin.ModelAdmin):
    list_display = ['title', 'language', 'status']

admin.site.register(Blog,AdminBlog )

Here, we create the class with the name AdminBlog. Then we create a list of the fields which we want to show on the admin panel. And last, register the model.

After this, create new migrations based on the changes you have made to your models. The command is as below:

python manage.py makemigrations

Then, applying and reapplying migrations. The command is as below:

python manage.py migrate

Then, open the shell to write a queryset. The command to open the shell is as below:

python manage.py shell

After this, insert and save the fields of the model.

# Import Libraries

from home.models import Blog
from home.models import BlogStatus

# Insert and Save Data Field 

a = Blog.objects.create(title="About Python",  language="Python", status=BlogStatus.P)

a.save()

b = Blog.objects.create(title="Install Python", language="Python", status=BlogStatus.S)

b.save()

c = Blog.objects.create(title="Data Types in Python", language="Python", status=BlogStatus.D)

c.save()

d = Blog.objects.create(title="About HTML", language="Python", status=BlogStatus.T)

d.save()

Now, the model is successfully created with the data fields.

Now, see how data looks in the admin panel.

python django text enum choices
Python Django text enum choices
python django get enum choices
Python Django get enum choices

Now, from the above outputs, you clearly see that here we pass the status as text enum choice symbol. But, it saves the full status name in the Blog Model automatically.

Example #2

In this example, we’ll take a field to identify the Publish Day of the post. We will use the given choices of Publish Day as Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and, Saturday. The following steps are being done to execute this example:

First, define the class for the choice:

# Import Library

from enum import Enum

# Create subclass of list

class PostPublished(Enum):   
    Sun = "Sunday"
    Mon = "Monday"
    Tue = "Tuesday"
    Wed = "Wednesday"
    Thur = "Thursday"
    Fri = "Friday"
    Sat = "Saturday"

Here, we create the subclass of the choice in the models.py file of the MyApp app directory with the name PostPublished.

Next, create the model:

# Import Library

from django.db import models

# Create Model

class Post(models.Model):
    title = models.CharField(max_length=255)
    language = models.CharField(max_length=100)
    PublishDay = models.CharField(max_length=4, choices=[(tag, tag.value) for tag in PostPublished])

Here, we create a model with the name Post in the model.py file of the MyApp app. And in this model, we define the title, language, and PublishDay fields. We use the above-defined PostPublished enum class in the PublishDay field of the model.

Then, define the admin part to view the table in the admin.

from django.contrib import admin
from .models import Post

class AdminPost(admin.ModelAdmin):
    list_display = ['title', 'language', 'PublishDay']

admin.site.register(Post,AdminPost)

Here, we create the class with the name AdminPost. Then we create a list of the fields which we want to show on the admin panel. And last, register the model.

After this, create new migrations and apply them. The commands are as below:

# Create migrations

python manage.py makemigrations

# Apply Migrations

python manage.py migrate

Then, open the shell to write a queryset to insert and save the fields of the model.

# Import Libraries

from MyApp.models import Post
from MyApp.models import PostPublished

# Insert and Save Data Field 

a = Post.objects.create(title="What is NumPy",  language="Python", PublishDay=PostPublished.Fri)

a.save()

b = Post.objects.create(title="Insert Data in MongoDB", language="MongoDB", PublishDay=PostPublished.Sun)

b.save()

c = Post.objects.create(title="Data Types in MySql", language="MySql", PublsihDay=PostPublished.Wed)

c.save()

d = Post.objects.create(title="About HTML", language="HTML", PublishDay=PostPublished.Thur)

d.save()

Now, the data fields are successfully added to the model.

Now, see how data looks in the admin panel.

text enum choices using django
Python Django get enum choices
text enum choices using python django
Python Django get enum choices

Now, as you can see from the outputs, we pass the publish day as a text enum choice symbol. However, it automatically preserves the complete publish day name in the Post Model.

Read: How to Create model in Django

Python Django integer enum choices

In this section, we’ll learn how we can store choices as an integer field in Django. So, we can get an enumeration based on an integer value using the enum.IntEnum() method. Let’s see different examples related to this.

Example #1

In this example, we’ll take a field to identify the status of the transaction. We will use the given choices of status as Successful, Pending, and Failed.

The following steps are being done to execute this example:

First, define the class for the choice:

# Import Library

from enum import IntEnum

# Create subclass

class TransactionStatus(IntEnum):
    Successful = 1
    Pending = 2
    Failed = 0

In the models.py file of the transaction app directory, we create the subclass with the name TransactionStatus.

Next, create the model:

# Import Library

from django.db import models

# Create Model

class AtmTransaction(models.Model):
    Pay_To = models.CharField(max_length=150)
    Amount = models.FloatField(max_length=5)
    status = models.CharField(max_length=25, choices=[(x, x.value) for x in TransactionStatus])  

Here, we create a model with the name AtmTransaction in the model.py file of the app. And in this model, we define the Pay_To, Amount, and status. We use the above-defined TransactionStatus enum class in the status field of the model.

Then, define the admin part in the admin.py file of the app to specify the view of the model in the admin panel.

from django.contrib import admin
from .models import AtmTransaction

class AdminAtmTransaction(admin.ModelAdmin):
    list_display = ['Pay_To', 'Amount', 'status']

admin.site.register(AtmTransaction,AdminAtmTransaction)

Here, we create the class with the name AdminAtmTransaction. Then we create a list of the fields which we want to show on the admin panel. And last, register the model.

After this, create new migrations and apply them.

Then, open the shell to write a queryset to insert and save the fields of the model.

# Import Libraries

from transaction.models import AtmTransaction
from transaction.models import TransactionStatus

# Insert and Save Data Field 

a = AtmTransaction.objects.create(Pay_To="Ava", Amount=500, status=TransactionStatus.Successful)

a.save()

b = AtmTransaction.objects.create(Pay_To="Oliver", Amount=1500.98, status=TransactionStatus.Failed)

b.save()

c = AtmTransaction.objects.create(Pay_To="Charlotte", Amount=2500.28, status=TransactionStatus.Pending)

c.save()

DataFeilds are successfully added in the AtmTransaction Model.

Now, see how data looks in the admin panel.

python django integer eum choices
Enum Status 1 means Successfully
python django get enum integer choices
Enum Status 0 means Failed

Now, as you can see from the outputs, we pass the Transaction Status as a complete name of the status. However, it automatically preserves the Status to Int Enum in the AtmTransaction Model.

Example #2

In this example, we’ll take a field to identify the availability of the color. We will use the given choices of ColorAvailability as Red, Green, Black, and Blue.

The following steps are being done to execute this example:

First, define the class for the choice:

# Import Library

from enum import IntEnum

# Create subclass

class ColorAvailability(IntEnum):
    Red = 1
    Green = 2
    Black = 3
    Blue = 4

In the models.py file of the cart app directory, we create the subclass with the name ColorAvailability.

Next, create the model:

# Import Library

from django.db import models

# Create Model

class Product(models.Model):
    Product_Name = models.CharField(max_length=150)
    Product_Amount = models.FloatField(max_length=5)
    Product_Color = models.CharField(max_length=25, choices=[(x, x.value) for x in ColorAvailability])  

Here, we create a model with the name Product in the model.py file of the app. And in this model, we define the Product_Name, Product_Amount, and Product_Color. We use the above-defined ColorAvailability enum class in the Product_Color field of the model.

Then, define the admin part in the admin.py file of the app to specify the view of the model in the admin panel.

from django.contrib import admin
from .models import Product

class AdminProduct(admin.ModelAdmin):
    list_display = ['Product_Name', 'Product_Amount', 'Product_Color']

admin.site.register(Product,AdminProduct)

Here, we create the class with the name AdminProduct. Then we create a list of the fields which we want to show on the admin panel. And last, register the model.

After this, create new migrations and apply them.

Then, open the shell to write a queryset to insert and save the fields of the model.

# Import Libraries

from cart.models import Product
from cart.models import ColorAvailability

# Insert and Save Data Field 

a = Product.objects.create(Product_Name="T-Shirt", Product_Amount=200.00, Product_Color=ColorAvailability.Red)

a.save()

b = Product.objects.create(Product_Name="Jump Suit", Amount=200.00, Product_Color=ColorAvailability.Green)

b.save()

c = Product.objects.create(Product_Name="Shirt", Product_Amount=800.00, Product_Color=ColorAvailability.Black)

c.save()

DataFeilds are successfully added to the Product Model.

Now, see how data looks in the admin panel.

integer enum choices using django
Product_Color 2 means Green
interger enum choices using python django
Product_Color 3 means Black

Also, take a look at some more Python Django Tutorials.

In this Python Django Tutorial, we discussed the Python Django get enum choices. Also, we discuss the following list of topics.

  • What is Enum
  • Why use Enum
  • When to use Enum
  • Python Django get enum choices
  • Python Django text enum choices
  • Python Django integer enum choices