1

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

<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))
4

1 回答 1

3

如果您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))

但是你可以尝试使用aggregate,像这样。

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}
于 2018-07-11T14:07:51.620 回答