Django Model Field Options: choices

By: Dusty Arlia
Published on Monday, March 10, 2014, 07:06 PM
Last Updated on Sunday, July 05, 2015 at 10:34 PM
Total Updates: 2

The choices field option is a list or tuple of 2-tuples. Here is an example:

APPLE_POSITIONS = (
    ('S', 'Specialist'),
    ('FRS', 'Family Room Specialist'),
    ('C', 'Creative'),
    ('G', 'Genius'),
    ('M', 'Manager'),
)

The first element in each tuple is the value that will be stored in the database. The second element will be displayed by the default form widget or in a ModelChoiceField. For choice fields, the default form widget will be a select box instead of the standard text field.

Get access to the display value of a choices field by using its field name in this method: get_[INSERT FIELD NAME]_display() (get_shirt_size_display()). Here's an example:

from django.db import models

class Employee(models.Model):
    SHIRT_SIZES = (
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
    )
    name = models.CharField(max_length=50)
    shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)
>>> p = Employee(name="Fred Flintstone", shirt_size="L")
>>> p.save()
>>> p.shirt_size
u'L'
>>> p.get_shirt_size_display()
u'Large'

Comments:

Ad:

Ad: