简体   繁体   中英

Django template how to look for a dictionary value while iterating another dictionary?

Template code snippet:

{% for stock in portfolio %}
   <tr>
      <td>{{ stock.stock_name }}</td>
      <td>{{ stock.trans_price }}</td>
      <td>{{ stock.trans_quantity }}</td>
      <td>{{ stock.trans_date }}</td>
      <td>{{ stock_ltps.stock.stock_name }}</td> <!-- This value doesn't get fetched. -->
   </tr>
{% endfor %}

View code snippet:

portfolio = Portfolio.objects.all()

# another dictionary to hold live stock prices from api 
stock_ltps = {}
for stock in portfolio:
    stock_ltps[stock.stock_name] = 12 #static number for debugging/trial

return render(request, 'portfolio_management/index.html', context={"stc": stock_name, "stock_add_form": stock_add_form, "portfolio": portfolio,
                           "stock_ltps": stock_ltps})

This doesn't fetch the value from another dictionary. How to fix this?

This is a common problem. One way to get round it is to use template tags. First, create a templatetag file (if one doesn't already exist). I'll call it tag_test.py:

from django.template.defaultfilters import register

@register.filter(name='dict_key')
def dict_key(d, k):
    '''Returns the given key (k) from a dictionary (d).'''
    return d[k].stock.stock_name

Then, in your template:

{% load tag_test %} 
{% for stock in portfolio %}
   <tr>
      <td>{{ stock.stock_name }}</td>
      <td>{{ stock.trans_price }}</td>
      <td>{{ stock.trans_quantity }}</td>
      <td>{{ stock.trans_date }}</td>
      <td>{{ stock_ltps | dict_key:forloop.counter0}}</td>
   </tr>
{% endfor %}

In the above script, the index of the loop, "forloop.counter0" is passed as an argument to the function "dict_key", which then returns the "stock.stock_name" components of the ith index.

(Please note I haven't tested the above code - if you can provide a fully workable example with test data I can produce an answer here known to work).

{% for stock in portfolio %}
   <tr>
      <td>{{ stock.stock_name }}</td>
      <td>{{ stock.trans_price }}</td>
      <td>{{ stock.trans_quantity }}</td>
      <td>{{ stock.trans_date }}</td>
   </tr>
{% endfor %}

{{ stock_ltps }}

Both item you have to call seperately

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM