在python
中,我可以轻松定义和重新定义变量。
(让变量为sum
):
>>> sum=0
>>> y=[1,2,3,4]
>>> for n in y:sum+=n
>>> sum
10
是否可以在django templates
??
我试过了:
{% with sum=0 %}
{% for emp in employees %}
<!--i dont want to print, but just redefine the variable sum -->
{{ sum|add:emp.credit }}
.........
{% endfor %}
<!-- now i want to print the sum. it is easy-->
{{ sum }}
{% end with %}
答案 0 :(得分:2)
这听起来不像是模板的工作。
最好在视图中定义sum
并将其传递给上下文中的模板,例如:
from django.db.models import Sum
total_credit = Employees.objects.all(). \
aggregate(total_credit=Sum('credit'))['total_credit']
return render_to_response('templatename.html',
{'total_credit': total_credit},
context_instance=RequestContext(request))