Django

Code

root/django/trunk/tests/modeltests/choices/models.py

Revision 8102, 1.1 kB (checked in by russellm, 1 month ago)

Fixed #7913 -- Corrected backwards incompatible parts of [7977] when optgroup handling was added to field choices (Ticket #4412). Thanks to Michael Elsdorfer (miracle2k) for the report and patch.

  • Property svn:eol-style set to native
Line 
1 """
2 21. Specifying 'choices' for a field
3
4 Most fields take a ``choices`` parameter, which should be a tuple of tuples
5 specifying which are the valid values for that field.
6
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.
10 """
11
12 from django.db import models
13
14 GENDER_CHOICES = (
15     ('M', 'Male'),
16     ('F', 'Female'),
17 )
18
19 class Person(models.Model):
20     name = models.CharField(max_length=20)
21     gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
22
23     def __unicode__(self):
24         return self.name
25
26 __test__ = {'API_TESTS':"""
27 >>> a = Person(name='Adrian', gender='M')
28 >>> a.save()
29 >>> s = Person(name='Sara', gender='F')
30 >>> s.save()
31 >>> a.gender
32 'M'
33 >>> s.gender
34 'F'
35 >>> a.get_gender_display()
36 u'Male'
37 >>> s.get_gender_display()
38 u'Female'
39
40 # If the value for the field doesn't correspond to a valid choice,
41 # the value itself is provided as a display value.
42 >>> a.gender = ''
43 >>> a.get_gender_display()
44 u''
45
46 >>> a.gender = 'U'
47 >>> a.get_gender_display()
48 u'U'
49
50 """}
Note: See TracBrowser for help on using the browser.