Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Browse files

Merge pull request #256 from ubernostrum/model-choice-docs

Fix #18062: Document best practices for choices in model fields.
  • Loading branch information...
2 parents db72926 + 7731cc8 commit b1517a310a0a9aa416bc479397d5a7b402be64e2 @ubernostrum ubernostrum committed
Showing with 26 additions and 25 deletions.
  1. +26 −25 docs/ref/models/fields.txt
51 docs/ref/models/fields.txt
@@ -86,42 +86,43 @@ field.
If this is given, Django's admin will use a select box instead of the standard
text field and will limit choices to the choices given.
-A choices list looks like this::
+A choices list is an iterable of 2-tuples; the first element in each
+tuple is the actual value to be stored, and the second element is the
+human-readable name. For example::
('FR', 'Freshman'),
('SO', 'Sophomore'),
('JR', 'Junior'),
('SR', 'Senior'),
- ('GR', 'Graduate'),
-The first element in each tuple is the actual value to be stored. The second
-element is the human-readable name for the option.
+Generally, it's best to define choices inside a model class, and to
+define a suitably-named constant for each value::
-The choices list can be defined either as part of your model class::
- class Foo(models.Model):
+ class Student(models.Model):
- ('FR', 'Freshman'),
- ('SO', 'Sophomore'),
- ('JR', 'Junior'),
- ('SR', 'Senior'),
- ('GR', 'Graduate'),
+ (FRESHMAN, 'Freshman'),
+ (SOPHOMORE, 'Sophomore'),
+ (JUNIOR, 'Junior'),
+ (SENIOR, 'Senior'),
- year_in_school = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES)
-or outside your model class altogether::
- ('FR', 'Freshman'),
- ('SO', 'Sophomore'),
- ('JR', 'Junior'),
- ('SR', 'Senior'),
- ('GR', 'Graduate'),
- )
- class Foo(models.Model):
- year_in_school = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES)
+ year_in_school = models.CharField(max_length=2,
+ default=FRESHMAN)
+ def is_upperclass(self):
+ return self.year_in_school in (self.JUNIOR, self.SENIOR)
+Though you can define a choices list outside of a model class and then
+refer to it, defining the choices and names for each choice inside the
+model class keeps all of that information with the class that uses it,
+and makes the choices easy to reference (e.g, ``Student.SOPHOMORE``
+will work anywhere that the ``Student`` model has been imported).
You can also collect your available choices into named groups that can
be used for organizational purposes::

0 comments on commit b1517a3

Please sign in to comment.
Something went wrong with that request. Please try again.