[Fixed]-Create a dictionary of dictionaries from a Django queryset

1👍

To answer your question, just do:

return {t.name : {'name': t.name, 
                  'icon': t.icon,
                  'description': t.description,
                  'queryset': self.get_queryset().get_type(t)
                 }
        for t in types}

But this is not necessary at all, django has some useful database lookups that are really handy. You don’t even need the code get_queryset().get_type(t), you could just do:

t.badge_set.all()

Here’s the doc that describes the RelatedManager usage, by default you use badge_set manager to do reverse lookups.

So in short, if you want to do something with the BadgeType objects, all you need is types = BadgeType.objects.all(), everything else comes with it.

You only pass your types queryset to the template, then in your template, do:

{% for badge_type in types %}
    <ul>{{ badge_type.name }}</ul>
    {% for badge in badge_type.badge_set.all %}
        <li>{{ badge.<attribute> }}</li>
    {% endfor %}
{% endfor %}

Leave a comment