2
21. Specifying 'choices' for a field
4
Most fields take a ``choices`` parameter, which should be a tuple of tuples
5
specifying which are the valid values for that field.
7
For each field that has ``choices``, a model instance gets a
8
``get_fieldname_display()`` method, where ``fieldname`` is the name of the
9
field. This method returns the "human-readable" value of the field.
12
from django.db import models
19
class Person(models.Model):
20
name = models.CharField(max_length=20)
21
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
23
def __unicode__(self):
26
__test__ = {'API_TESTS':"""
27
>>> a = Person(name='Adrian', gender='M')
29
>>> s = Person(name='Sara', gender='F')
35
>>> a.get_gender_display()
37
>>> s.get_gender_display()
40
# If the value for the field doesn't correspond to a valid choice,
41
# the value itself is provided as a display value.
43
>>> a.get_gender_display()
47
>>> a.get_gender_display()