Working properly with Django Choices
April 17, 2018 ·
2 mins read
The default implementation of choices in Django is not very intuitive and we repeat a lot of code while using them. Django choices act as an
enum
for the fields. We can choose from the various options whose value can be assigned to a given field.
While writing models you expect that you might be looking at neat fields that are used to store data. But when you introduce choices in Django it becomes cumbersome.
1. Default choices implementation in Django docs
2. Implementing Django Choices using djchoices module
By default, Django choices are written as tuples inside tuples. A simple example can be a fancy animal problem.
2. Implementing Django Choices using djchoices module
Default choices implementation in Django docs
animal = (
('cat', '0'),
('lizard', '1'),
('dog', '2'),
)
animal_type = models.CharField(choices=animal, max_length=2)
animal_type
is the only data that is going to be stored in the database. For that, we wrote a lot of extra things in the model file.
If you are using a Python version greater than 3.4
. You can make something with the enum and create a very sophisticated version of your own, but if you are using anything below 3.4
you have to use some other implementation.
This one looked good to me on the first look. The documentation showed every possible use case.
Django-choices
You can use this module as follows.
Implementing Django Choices using djchoices module
# choices.py
from djchoices import DjangoChoices, ChoiceItem
class PersonType(DjangoChoices):
customer = ChoiceItem("C")
employee = ChoiceItem("E")
groundhog = ChoiceItem("G")
# models.py
from .choices import PersonType
class Person(models.Model):
type = models.CharField(max_length=1, choices=PersonType.choices)
Please share your Feedback:
Did you enjoy reading or think it can be improved? Don’t forget to leave your thoughts in the comments section below! If you liked this article, please share it with your friends, and read a few more!