3

I have a structure my_dict like this:

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?

43Tesseracts
  • 4,617
  • 8
  • 48
  • 94

1 Answers1

3

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

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

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

{% endfor %}
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • 1
    Thanks. If I pass `my_dict` in the context and try to get `my_dict.items` in the template, it fails:`{{my_dict.items}} = []` but I tried passing `my_dict.items()` in the context, and it works?! I don't understand. – 43Tesseracts Sep 27 '15 at 20:37
  • I don't think it is possible. http://stackoverflow.com/questions/8018973/how-to-iterate-through-dictionary-in-a-dictionary-in-django-template I am not able to make more comments as I don't know what else you are doing in the template and the view. – Ozgur Vatansever Sep 27 '15 at 20:40