How to iterate over nested dictionaries in django templates

后端 未结 3 1415
陌清茗
陌清茗 2020-12-05 02:27

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

3条回答
  •  一生所求
    2020-12-05 02:50

    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 %}
          

      {{ data.grouper }}

      # 'apples' {% regroup data.list by date as data_by_fruits_date %} {% for data_1 in data_by_fruits_date %}

      {{ data_1.grouper }}

      # '2011-07-23' {% for datapoint in data_1.list %} total: {{ datapoint.total }}
      good: {{ datapoint.good }}
      {% endfor %} {% endfor %} {% endfor %}

提交回复
热议问题