1

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 %}
4

1 回答 1

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))
于 2013-09-27T07:56:05.537 回答