Wednesday, January 25, 2012

Re: get_FOO_display() for generic/variable choice fields

My Python-expert partner suggested a clever workaround as follows:

As I'm already running through the model._meta.fields beforehand to
create header row for my .csv file, I can build a dictionary of the
choices to refer to later.

choices_lookup_dict = {}
header_row = []

for field in model._meta.fields:
# create header row for csv file
header_row.append(field.name)
# Add lookup dictionary of choices to dictionary of fields
# i.e. creating a dictionary of dictionaries for each choice field
if field.choices:
choices_lookup_dict[field.name] = dict(field.choices)

This could be quite expensive for large choice tuples such as country
lists, but at least we're only calling it once.

So now in my main loop I can use the following code to lookup my
verbose choice value:


for field in model._meta.fields:
val = getattr(obj, field.name)
if field.choices:
val = choices_lookup_dict[field.name][val]
row.append(val)


We assume that get_FOO_display() must be doing something like this
anyway!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate