Iterate a list in Django

0

I have a model called Precompra and from there I am interested in the price to calculate the total for now. What is the problem with this code that is not showing me the result in the template.

This code was programmed in view.py :

def precio_pactado(request):
    aux = 0
    precompra=list(Precompra.objects.all())
    for compras in precompra:
        aux = compras.precio + compras.precio
    return render(request, 'carrito.html', locals())

Any ideas?

    
asked by Roberto Cárdenas 13.04.2017 в 17:48
source

1 answer

2

There is a logical error when making the addition in the for since the value of the variable aux siempre será el doble del ultimo elemento , the modification would be simple, make the addition to the variable aux , also it is not necessary to convert to Lista to be able to iterate.

def precio_pactado(request):
    aux = 0
    precompra=Precompra.objects.all()
    for compras in precompra:
        aux +=compras.precio
    return render(request, 'index.html', locals())

Then in the template Print this value with {{ aux }}

Additional suggestion to do the sum directly without iterating the elements. using aggregation

from django.db.models import Sum
totaldos =  Precompra.objects.aggregate(Sum('precio')).values()[0]
    
answered by 13.04.2017 / 18:58
source