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

最佳答案

这听起来不像是模板的工作。

最好在视图中定义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))

09-10 13:26
查看更多