lovefaithswing
lovefaithswing

Reputation: 1540

django template find dictionary in list

This may be super easy, but I've read through the docs and can't find anything.

I have a list that looks like: [{foo: 2, bar: 5},{foo: 3, bar: 4}]

Where foo is actually an object id. bar is generated from a values.annotate query.

So now I am looping over my items and I need to display the bar value for each foo, pulling it from the list. Is there a way to do this in the django template?

So I'd need a template tag or filter that pulled the dictionary from the list where foo value equals the id of the object I am working with. (Besides for x in list: if x.foo = #:, since the will be a lot of dicts in my list and that seems cluncky.)

Upvotes: 1

Views: 689

Answers (1)

Michael C. O'Connor
Michael C. O'Connor

Reputation: 9890

I think it will probably be better if, rather than trying to deal with this data structure in the template, you collapse that into a dict like:

aggregate_dict = {<id_1>:<val_1>,...}

so that you can more easily look up the values in the template as {{aggregate_dict.<id_n>}} instead.

you could do that with a little loop like:

aggregate_dict = {}
for item in your_old_list:
  aggregate_dict[item[foo]] = item[bar]

Upvotes: 2

Related Questions