How to iterate over nested dictionaries in django templates

吃可爱长大的小学妹 提交于 2020-01-09 13:21:30

问题


I'm not sure the most efficient way to iterate over my nested dictionaries to print a matrix of the total and good values for every fruit for each date. Take for instance the two lists and dictionary below:

fruits = ['apples','oranges','bananas']
harvest_dates = ['2011-07-23','2011-07-22','2011-07-21']

harvest_data = {
  'apples': {
    '2011-07-23': {
      'total': 100,
      'good': 80},
     '2011-07-22': {
       'total': 97,
       'good': 92},
     '2011-07-21': {
       'total': 90,
       'good': 85}
  },
  'oranges': {
    '2011-07-23': {
      'total': 86,
      'good': 82},
    '2011-07-22': {
      'total': 90, 
      'good': 75},
    '2011-07-21': {
      'total': 92,
      'good': 92}
  },
  'bananas': {
    '2011-07-23': {
      'total': 10,
      'good': 9},
    '2011-07-22': {
      'total': 12, 
      'good': 11},
    '2011-07-21': {
      'total': 9,
      'good': 9}
  }
}

I can easily do this in python:

for fruit in fruits:
  for day in harvest_dates:
    print "harvest: %s" % harvest_data[fruit][day]['total']
    print "good crop: %s" % harvest_data[fruit][day]['good']

But I don't know how to access this data in django templates. I had been trying something such as:

{% for fruit in fruits %}
  ...
  {% for day in harvest_dates %}
    ...
    {{ harvest_data.fruit.day.total }}
    {{ harvest_data.fruit.day.good }}
    ...
  {% endfor %}
{% endfor %}

But it's simply not working.

{% for fruit in fruits %}
  {{ harvest_data.fruit }}  <--- this does not exist
  {{ harvest_data[fruit] }}  <--- this does not work
{% endfor %}

I'm a complete amateur and I'm probably going about this all wrong, but I've Google'd quite a bit and it's not clear to me what the best approach to getting the data I want is.


回答1:


Since you're familiar with python, the following is logically how you would want to iterate through your dictionary in a Django template:

for key,value in harvest_data.items():
...     print key
...     for key2,value2 in value.items():
...         print key2
...         for key3,value3 in value2.items():
...             print "%s:%s"%(key3,value3)

In your template, this translates as follows:

{% for key, value in harvest_data.items %}
    {{ key }} <br>
    {% for key2,value2 in value.items %}
        {{ key2 }} <br>
        {% for key3, value3 in value2.items %}
            {{ key3 }}:{{ value3 }} <br>
        {% endfor %}
    {% endfor %}
{% endfor %}

The Django docs actually briefly include an example of how to iterate through dictionaries when describing how the for template tag works:

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for




回答2:


as rolling stone says thats the way to iterate over dictionaries in templates, i would only change the key, value keywords for different keywords in every iteration like this:

{% for key, value in harvest_data.items %}
    {{ key }} <br>
    {% for key2,value2 in value.items %}
        {{ key2 }} <br>
        {% for key3, value3 in value2.items %}
            {{ key3 }}:{{ value3 }} <br>
        {% endfor %}
    {% endfor %}
{% endfor %}

just for the sake of clarity :)

And if you want to line up your values i would suggest you use another data structure where you can sort by date, for example a something like this:

{ 'oranges' : [(date1, value1), (date2,value2)] ...}

Try to do the least possible operations in your templates, so dont do a sort or nested if's if you dont have to




回答3:


Really old question, but I will add my 1.5c.

This is a good use case of the regroup tag (https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#regroup) and a bit of data refactoring:

  1. Have your data as a simple list of data points:

    harvest_data = [
        {'fruits': 'apples', 'date': '2011-07-23', 'total': 100, 'good': 80},
        # ...
    ]
    
  2. In your template, group by the chosen dimension(s):

    {% regroup harvest_data by fruits as data_by_fruits %}
    {% for data in data_by_fruits %}
        <h1>{{ data.grouper }}</h1>   # 'apples'
        {% regroup data.list by date as data_by_fruits_date %}
        {% for data_1 in data_by_fruits_date %}
            <h2>{{ data_1.grouper }}</h2>    # '2011-07-23'
            {% for datapoint in data_1.list %}
                total: {{ datapoint.total }} <br/>
                good: {{ datapoint.good }} <br/>
            {% endfor %}
        {% endfor %}
    {% endfor %}
    


来源:https://stackoverflow.com/questions/6803599/how-to-iterate-over-nested-dictionaries-in-django-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!