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

Enum stands for Enumeration. Enumeration is a collection of symbolic names that are linked to distinct constant values. In other words, enum is a way to provide names to a collection of distince values.

From programming perspective, instead of remembering raw numbers or string codes, you can give human readable names for that numbers or string codes. By using enum, your code seems more cleaner and understandable.

  • For example suppose you have tv remote and when you press the button 0 which means turn off the tv and press the button 1 to turn on the tv.
  • Instead of remembering the number 0 and 1, you can use enum to provide a human readable name, such as the red color button to turn off the tv and the green color button to turn on the tv.

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.

Now you know about what enum are and why or when to use the enum. But how to define enum in your Django project.

To define any class as enum in Django, For that look at the below code

# Import Library

from enum import Enum

# Create enum using class

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

In the above code import the Enum class from the module enum in Python, then to define any class as enum inherit the Enum to that class.

Read: Django for loop

Python Django get enum choices

In Django, to define choices for a Field in the Model use then 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

Using enum, let’s know how to store choices as a text field in Django. For example, suppose you are building a blog website and have to track the blog post status such as whether the post is scheduled, published, in draft or trash.

READ:  Matplotlib Pie Chart Tutorial

For that look at the below code how to define the class as enum.

from enum import Enum

class BlogStatus(Enum):
    DRAFT = ('D', 'Draft')
    PUBLISHED = ('P', 'Published')
    SCHEDULED = ('S', 'Scheduled')
    TRASH = ('T', 'Trash')

    @classmethod
    def get_choices(cls):
        return [(status.value[0], status.value[1]) for status in cls]

In the above code, importing the Enum class from the enum module. Then define the new class named BlogStatus which inherit the Enum class.

Within the class BlogStatus, there are four distinct values Published, Draft, Scheduled and Trash. Each values is connected with a tuple, the first value is the short code for example (‘D’ for Draft) and the second element is the full name (‘Draft’).

After that define the class method within the enum class BlogStatus. This method, identified by the @classmethod decorator, is part of the BlogStatus Enum.

  • Its purpose is to return a selection of choices for a Django model field.
  • The method goes through each member or values of the Enum class BlogStatus such as DRAFT or PUBLISHED, and generates a list of tuples that includes both the short code and full name.

Next, create the model BlogPost and add the following line of codes.

class BlogPost(models.Model):
    status = models.CharField(
        max_length=2,
        choices=BlogStatus.get_choices(),
        default=BlogStatus.DRAFT.value[0],
    )

In the above code defining the Django model named BlogPost with field status of type CharField.

  • The field status should not contains more than 2 characters which is specified using max_length=2 for example ‘P’ for published or ‘T’ for trash.
  • Next choices=BlogStatus.get_choices(), this property means use only the predefined list of values. If you have remember, you defined the method get_choices() in your enum class BlogStatus.

Finally the code default=BlogStatus.DRAFT.value[0] automatically set the status of new created blog to ‘D’ which means blog is in the draft mode.

  • Where DRAFT.value[0] means the first value of tuple (‘D’, ‘Draft’), here the value at 0th position is ‘D’ and at 1st position is the ‘Draft’.

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(BlogPost,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.

READ:  np.genfromtxt() Function in Python [5 Examples]

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.

READ:  How to attach an image in Turtle Python

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