Enumerate() in Python
The enumerate() method adds counter to an iterable and returns it (the enumerate object).
enumerate()
method takes two parameters:
enumerate()
starts counting from this number. If start is omitted, 0
is taken as start
.Now let's how we could use Enumerate in Django Framework.
Below Django example only < Django 3.0 version. In Django 3.0 there is TextChoiceField introduced, where we could use the enum directly.
Django Enumerate ChoiceField
Example:
APPROVE_CHOICE = ['APPROVED','PENDING']
enumerateChoice = enumerate(APPROVE_CHOICE)
print(type(enumerateChoice))
# converting to list
print(list(enumerateChoice))
# changing the default counter
enumerateChoice = enumerate(APPROVE_CHOICE , 5)
print(list(enumerateChoice))
Output
<class 'enumerate'>
[(0, 'APPROVED'), (1, 'PENDING')]
[(5, 'APPROVED'), (6, 'PENDING')]
In this post, I will walk you through using Enum as choices of field with a simple example. Assume there is a Post model where we need to enable the APPROVED/PENDING choice type in our choice Field.
First, we define a class for all choices:
class Post(models.Model):
title = models.CharField(max_length=60)
status = models.CharField(
blank=True, choices=[(stat, stat.value) for stat in StatusType], max_length=20)
Now we have defined our Enums and model, how would we use it?
class StatusType(Enum):
APPROVED = "APPROVED"
PENDING = "PENDING"
Below are the way to create the enum related field
>>> from blog.models import Post
>>> from enum import Enum
>>> class StatusType(Enum):
... APPROVED = "APPROVED"
... PENDING = "PENDING"
...
>>> p = Post(title='hi',status=StatusType.PENDING)
>>> p.save()
Note that how we supply the value for parameter status depends on the first element we defined in the Tuples of the list of choices. We use (stat, stat.value) which stat being an Enum type.
Below details, I have grabbed from some of the various article,
You may ask, “Why using Enum instead of the examples given in Django official documentation?”
According to PEP 435, an enumeration are useful for defining an immutable, related set of constant values that may or may not have a semantic meaning. Classic examples are days of the week (Sunday through Saturday) and school assessment grades (‘A’ through ‘D’, and ‘F’). Other examples include error status values and states within a defined process.
good