Next Post:
Previous Post:

Django models have a great function get_FOO_display (which is actually _get_FIELD_display) that return the display name of the options that correlate to the stored value of the model.

To explain with an example

For a Charfield Model with the following declaration

textexamplefield = Model.Charfield(
max_length = 1,
choices = EXAMPLE_OPTIONS
)
EXAMPLE_OPTIONS = (
('u','undefined'),
('t','true'),
('f','false')
)

In the above, an instance with value ‘t’ for texamplefield will return true with the call: instance.get_textexamplefield_display.

Now going to another example:

integerexamplefield = Model.IntegerField(
choices = INT_EXAMPLE_OPTIONS
)
INT_EXAMPLE_OPTIONS  = (
('0','Option 0'),
('1','Option 1'),
('2','Option 2')
)

For this example, get_integerexamplefield_display will not work.

But declaring INT_EXAMPLE_OPTIONS as:
INT_EXAMPLE_OPTIONS  = (
(0,'Option 0'),
(1,'Option 1'),
(2,'Option 2')
)

will result in get_integerexample_field working as normal.
Just note the integer and character relation while declaring the options variable.