Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django sum of row in template for loop

Tags:

python

django

I want to show sum of subtotal in my template.

{% for quote in quotes %}
    {% for product in quote.purchase_quote_products_set.all %}
        {{product.subtotal}} | 
    {% endfor %}
    <span id="total"></span>
{% endfor %}

my result.

15 | 120 | 2000 |

Is there any way to show sum of subtotal inside span#total

<span id="total">{{ sum_of_subtotal }}</span>
like image 525
SAFEER N Avatar asked Jan 28 '14 11:01

SAFEER N


2 Answers

It is best to perform such arithmetic in Django views rather than templates. For e.g. you can find the sum in the view itself:

from django.db.models import Sum
total_price = Quotes.objects.all().annotate(total=Sum('purchase_quote_products__subtotal'))

Then the template can use:

<span id="total">{{ quote.total }}</span>
like image 137
arocks Avatar answered Nov 08 '22 20:11

arocks


If you are trying to calculate on the template, then in Django Template there is something called filter which are use to alter values of variables before they’re render to UI.

Custom filters are just Python functions that take one or two arguments:

  • The value of the variable (input) – not necessarily a string.
  • The value of the argument – this can have a default value, or be left out altogether.
  • For example, in the filter {{ var|foo:"bar" }}, the filter foo would be passed the variable var and the argument "bar".

Filter functions should always return something. They shouldn’t raise exceptions. They should fail silently. In case of error, they should return either the original input or an empty string – whichever makes more sense.

Here’s an example filter definition:

def cut(value, arg):
    """Removes all values of arg from the given string"""
    return value.replace(arg, '')

And here’s an example of how that filter would be used:

{{ somevariable|cut:"0" }}

Please read the following docs for more information, custom_template

like image 34
James Avatar answered Nov 08 '22 20:11

James