我想计算模板中购物车的总数: 这是我的带有产品表的模板。 我试图在购物车方法中使用Generator表达式,但是它不起作用。 有什么想法吗?
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))
答案 0 :(得分:1)
如果您希望total_prices
在context
中可见,请将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))
变量中。
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}
但是您可以尝试使用aggregate之类的东西。
docker run -d -p 1433:1433 -e sa_password=testing1234 -e ACCEPT_EULA=Y microsoft/mssql-server-windows-developer -v "C:\test\Microsoft SQL Server":"C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\"