accessing dictionary in a template

178 views
Skip to first unread message

cesco

unread,
Jun 16, 2007, 9:17:07 AM6/16/07
to Django users
Hi,

I'm using the django-voting application whose method
get_votes_in_bulk(object) returns a "votes" dictionary like:
{object_id: {''score': score, 'num_votes': num_votes}

I'm passing this dictionary as extra_context to a template where I'm
also using the regroup tag on theobjects which I pass as the main
queryset.

So I would need to access the score and the num_votes as follow on a
specific item base (I can't iterate sequentially over the items due to
the regrouping). To be precise I would need to access as follow:

{{ votes.object.id.score }}

Of course this doesn't work because we can only use
votes.object_id.score but not votes.object.id.score. Instead I need to
first lookup the id and then access the dictionary using this id.

If it was python I could have done something like:
votes[object.id]['score']

Is there a way to do so in a template?

Thanks
Francesco

Malcolm Tredinnick

unread,
Jun 16, 2007, 6:23:32 PM6/16/07
to django...@googlegroups.com

No, you can't do indirect references (the vote[object.id] part) like
this in templates.

The usual recommended solution is to rejig the data structures a little
bit when you find yourself needing to do this. Instead of using the
value of one data structure to index into a second structure, put them
all into one data structure so that all the information is available at
once. How to do this depends on the particular application -- there
isn't always a general recipe.

Regards,
Malcolm

Reply all
Reply to author
Forward
0 new messages