Working properly with Django Choices
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
enumfor 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.
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_typeis 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.4you 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)
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!