首页 > 解决方案 > Summing a column after filtering Django 2.1

问题描述

This is my for loop (in my template.html):

{% for item in filter.qs %}
    <tr>
    <th scope="row">{{ item.id }}</th>
    <td>{{ item.nome }}</td>
    <td>{{ item.data|date:"d, F" }}</td>
    <td>{{ item.tipo_pgto}}</td>
    <td>{{ item.mes }}</td>
    <td>{{ item.entrada }}</td>
    <td>{{ item.valor}}</td>
    </tr>
{% endfor %}

The variable {{ item.valor }} holds a decimal number after filtering. How can I sum it and put the result in another part of my HTML? Is the better practice use now JavaScript or there is a way like creating a variable in my view.py and then place it in html?

标签: djangotemplatesfilterviewsum

解决方案


Doing it in JS would be fine, but IMO passing it through the context from the view is better. JS is much harder to do tests for.

If you use Jinja templates (really easy to set up and to use), you could use their filters:

{{ filter.qs | sum(attribute='valor') }}


推荐阅读