Thoughts inspiring. Inspiring thoughts
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.
ThinkingNectar talks about the interest of Chin Yong, a PHP/Python/Web developer residing in Singapore. Life, society, and codes should entails most of what goes between the ears of this coffee drinker.
What makes you think?
Arsento
November 4th, 2009 at 6:15 am
In truth, immediately i didn’t understand the essence. But after re-reading all at once became clear.
Arsento
November 13th, 2009 at 1:51 am
I really like your blog and i respect your work. I’ll be a frequent visitor.
Luke
April 6th, 2010 at 10:58 am
I was stumped when get_foo_display would return only integers for me. This helped solve my issue. Thanks!