Django行循环中的行模板 [英] Django sum of row in template for loop

查看:94
本文介绍了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 %}

我的结果

15 | 120 | 2000 |

有没有办法在 span#total

<span id="total">{{ sum_of_subtotal }}</span>


推荐答案

最好在Django视图中执行这种算术比模板。例如您可以在视图中找到总和:

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'))

然后模板可以使用:

<span id="total">{{ quote.total }}</span>

这篇关于Django行循环中的行模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆