Sum of objects' prices in Django template

自闭症网瘾萝莉.ら 提交于 2021-01-28 08:18:46

问题


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

回答1:


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}


来源:https://stackoverflow.com/questions/51287539/sum-of-objects-prices-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!