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

时间:2021-07-28 20:19:25

I have a structure my_dict like this:

我有一个像my_dict这样的结构:

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

I want to loop through the objects something like this:

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

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

How do I loop through the things in this nested loop? myobject1 is not iterable, so how do I get the iterable?

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

1 个解决方案

#1


2  

You should loop through .items() of the dictionary to get both object and the list in hand at each iteration:

您应该遍历字典的.items()以在每次迭代时获取对象和列表:

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

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

{% endfor %}

#1


2  

You should loop through .items() of the dictionary to get both object and the list in hand at each iteration:

您应该遍历字典的.items()以在每次迭代时获取对象和列表:

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

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

{% endfor %}