How to iterate dictionary to template in Django

Question:

I have two loops that works perfect if I print the results. It gives me a list that show the name and the value but I have difficulties to show it in a template. It just shows the last results.

for u in Performance.objects.raw('SELECT * FROM...')
    name = u.last_name + ' ' + u.first_name

    for e in Projekt_perf.objects.raw('SELECT stressz_profile.id...')
        total = e.total

        results = {'name':name, 'total':total}


     context = {
        'results': results,
        'name': name,
        'total': total,    
        }

        return render(request, 'performance/list.html', context)`

This is the dictionary I get, it’s OK:
{'name': 'Someone01', 'total': 25} {'name': 'Someone02', 'total': 7} {'name': 'Someone03', 'total': 10} {'name': 'Someone04', 'total': 0}

I like to have the dictionary above in the template and I tried these methods but I did not get all the elements just the last one.
{% for r in results %} {{ r }} {% endfor %}

{% for r in results %} {{ r.name }} - {{ r.total }} {% endfor %}

What am I doing wrong?

Asked By: Oriza

||

Answers:

Try this code you need to append all objects in list then after iterate it. like this …

    final_data = []
    total =0
    for u in Performance.objects.raw('SELECT * FROM...')
        name = u.last_name + ' ' + u.first_name
        for e in Projekt_perf.objects.raw('SELECT stressz_profile.id...')
            total = e.total
            final_data.append({'name':name, 'total':total})
    context = {
    'results': final_data,
    'total': total,    
    }
    return render(request, 'performance/list.html', context)

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.