python - Django 循环模板中行的总和

标签 python django

我想在我的模板中显示小计总和。

{% 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 View 而不是模板中执行此类算法。例如您可以在 View 本身中找到总和:

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

那么模板可以使用:

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

关于python - Django 循环模板中行的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21404051/

相关文章:

python - 有没有办法获取特定版本 Python 的内在运算符列表?

python - 使用 Python 从 SFTP 服务器下载超过 5 天的文件

python - 空 {{ MEDIA_URL }} 标签,由从 Django 1.7.2 过渡到 1.8 引起

javascript - 如何读取Django中下拉菜单的内容?

django - 如何在django中找回密码

python - 为什么这段代码有这个错误: "Expected:)"?

python - 如何将列表转换为pandas DataFrame?

python - 我怎样才能让 2 个类引用同一个类的实例

django - 如何测试登录过程?

python - 在 django-channels 中等待 websocket.receive 消费者