Django模板中的对象价格总和 [英] Sum of objects' prices in Django template
本文介绍了Django模板中的对象价格总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算模板中购物车的总数:这是我的带有产品表的模板.我试图在购物车方法中使用Generator表达式,但是它不起作用.有什么想法吗?
I would like to compute the total of a shopping cart in my template: This is my template with a table of products. I tried to use a Generator expression in my cart method but it doesn't work. Any thoughts?
cart.html
cart.html
<table>
{% if not cart_list %}
{{ "The cart is empty" }}
{% else %}
<tr>
<th>Name</th>
<th>Price</th>
</tr>
{% for product in cart_list %}
<tr>
<td>{{ product.name }}</td>
<td>${{ product.price }}</td>
</tr>
{% endfor %}
<tr>
<td>{{ Total }}</td>
<td>{{ total_prices }}</td>
</tr>
{% endif %}
</table>
views.py
def cart(request):
if request.method == 'GET':
cart_list = Product.objects.filter(in_cart = True)
total_prices = sum(product.price for product in cart_list)
template_cart = loader.get_template('cart/cart.html')
context = {'cart_list': cart_list}
return HttpResponse(template_cart.render(context, request))
推荐答案
将您的 total_prices
添加到 context
变量中(如果希望在中可见)模板
.
Add your total_prices
to context
variable, if you want it to be visible in the template
.
def cart(request):
if request.method == 'GET':
...
total_prices = sum(product.price for product in cart_list)
context = {
'cart_list': cart_list,
'total_prices': total_prices
}
return HttpResponse(template_cart.render(context, request))
But you can try to use aggregate, something like this.
from django.db.models import Sum
Product.objects.filter(in_cart=True).aggregate(Sum('price'))
# you will have something like this -> 34.35 is example
# {'price__sum': 34.35}
这篇关于Django模板中的对象价格总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文