Django Model Choices provides a neat and DRY way to specify the `choices` option for a Django models and forms.
pip install django-model-choices==1.0.0
Django Model Choices (DMC) provides a convenient and DRY way to specify the choices
option for a Django model field.
from modelchoices import Choices
class AnimalChoices(Choices):
MAMMAL = ('m', 'a mammal')
BIRD = ('b', 'a bird')
REPTILE = ('r', 'a reptile')
The value of each choice must be a tuple containing a value for the database and a user readable value.
An extra attribute CHOICES
is generated 'magically'. This can be used in the Model's Field definition.
class Animal(models.Model):
phylum = models.CharField(max_length=1, choices=AnimalChoices.CHOICES)
The variables MAMMAL
, BIRD
and REPTILE
can be used to programmatically represent the choice values. Once the class is created, their values are no longer a tuples, but only the database fields (so AnimalChoices.MAMMAL
is equal to 'm'
). So you can do
animal = Animal()
animal.phylum = AnimalChoices.MAMMAL
animal.save()