Django / Python:计算django模板中项目的总量
Django / Python: Calculate total amount of item in django template
如何在 Django 模板中计算总数?
假设我想生成客户订单清单,例如:
我有以下数据:
obj = [{"location": "name", "timeSlot": '09:30 PM', "price": 2}, {"location": "name", "timeSlot": '09:30 PM', "price": 1}, {"location": "name", "timeSlot": '09:30 PM', "price": 3}, {"location": "name", "timeSlot": '09:30 PM', "price": 2}, {"location": "name", "timeSlot": '09:30 PM', "price": 4}]
所需的报告输出
--------------------
09:30 PM
--------------------
1 name $ 2
2 name $ 1
3 name $ 3
4 name $ 4
------------------------
Total $ 10
模板不适合执行此操作。您应该在您的视图或模型中执行此操作。例如,在您收到订单后,您可以这样做:
orders=order.objects.filter(id=timeslot)
total = 0
for order in orders:
total += order['price']
return render(request, 'your_template', {'orders': orders, 'total': total})
现在,总计将与订单一起出现在您的模板中
我为此使用了自定义过滤器。
这是我的 customFilter.py 代码
from django import template
register = template.Library()
@register.filter
def slotTotalAmount(arg):
return sum(d.get('price') for d in arg)
这是我的 django 模板代码
{% load custom_filters %}
<span class="pull-left" ><b>Total</b></span>
<span class="pull-right"><b>{{Obj|slotTotalAmount|floatformat:0}}</b></span>
很容易写一个并在两种情况下给出相同的输出,即写在 view.py 和 customFilter.py 中。
如何在 Django 模板中计算总数?
假设我想生成客户订单清单,例如:
我有以下数据:
obj = [{"location": "name", "timeSlot": '09:30 PM', "price": 2}, {"location": "name", "timeSlot": '09:30 PM', "price": 1}, {"location": "name", "timeSlot": '09:30 PM', "price": 3}, {"location": "name", "timeSlot": '09:30 PM', "price": 2}, {"location": "name", "timeSlot": '09:30 PM', "price": 4}]
所需的报告输出
--------------------
09:30 PM
--------------------
1 name $ 2
2 name $ 1
3 name $ 3
4 name $ 4
------------------------
Total $ 10
模板不适合执行此操作。您应该在您的视图或模型中执行此操作。例如,在您收到订单后,您可以这样做:
orders=order.objects.filter(id=timeslot)
total = 0
for order in orders:
total += order['price']
return render(request, 'your_template', {'orders': orders, 'total': total})
现在,总计将与订单一起出现在您的模板中
我为此使用了自定义过滤器。
这是我的 customFilter.py 代码
from django import template
register = template.Library()
@register.filter
def slotTotalAmount(arg):
return sum(d.get('price') for d in arg)
这是我的 django 模板代码
{% load custom_filters %}
<span class="pull-left" ><b>Total</b></span>
<span class="pull-right"><b>{{Obj|slotTotalAmount|floatformat:0}}</b></span>
很容易写一个并在两种情况下给出相同的输出,即写在 view.py 和 customFilter.py 中。