循环遍历django模板中的defaultdict(list)结构

时间:2015-09-27 20:08:48

标签: python django django-templates

我有这样的结构my_dict

defaultdict(<class 'list'>, {
   <MyClass: myobject1>: [<ThingClass: mything1>, <ThingClass: mything2>, ...],
   <MyClass: myobject2>: [<ThingClass: mything6>, <ThingClass: mything7>, ...], 
   <MyClass: myobject3>: [<ThingClass: mything45>, <ThingClass: mything46>, ...],
   ...
})

我想循环遍历这样的对象:

{% for object in my_dict %}
    {{object.somefield}}    
      {% for thing in object %}
          {{thing.somefield}}
      {% endfor %}
  {% endfor %}

如何遍历此嵌套循环中的内容? myobject1不可迭代,所以如何获得可迭代的?

1 个答案:

答案 0 :(得分:2)

你应该循环遍历字典的.items(),以便在每次迭代时获得对象和列表:

{% for obj, things in my_dict.items %}
    {{obj.somefield}}

    {% for thing in things %}
        {{thing.somefield}}
    {% endfor %}

{% endfor %}