Home > OS >  Iterating over queryset of dictionary
Iterating over queryset of dictionary

Time:12-19

I have a queryset dict which I want to access in template, I have following queryset:

<QuerySet [{'membership__name': 'm1', 'membership_count': 2}, {'membership__name': 'm2', 'membership_count': 1}]>

I have tried some options but can't seem to get what I want.

{% for key, value in reports_data %} 
     {{key}} : {{value}}  // I only get key not value
{% endfor %}

Can anyone please help me how can I do it.

CodePudding user response:

You can typecast a QuerySet to list in python using - reports_data = objects.all() #Your query set

list_data = list(reports_data)

If you want to iterate through this list_data

for element in reports_data:
    for key, value in element.items():
        print(key, value)

CodePudding user response:

You should iterate the QuerySet first then iterate the dictionaries in the second loop and don't forget the .items().

{% for element in reports_data %}
     {% for key, value in element.items() %}
         {{key}} : {{value}}
     {% endfor %}
{% endfor %}
  • Related