【问题标题】:Sum of objects' prices in Django templateDjango模板中对象价格的总和
【发布时间】:2018-12-19 14:47:37
【问题描述】:

我想计算模板中购物车的总数: 这是我的带有产品表的模板。 我尝试在我的购物车方法中使用生成器表达式,但它不起作用。 有什么想法吗?

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 添加到您的上下文对象中,以便可以从模板页面访问它。
  • 感谢您的快速回复!

标签: python django django-templates sum generator-expression


【解决方案1】:

如果您希望它在template 中可见,请将您的total_prices 添加到context 变量。

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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 2017-11-24
    • 2014-02-19
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 2016-11-12
    • 2017-11-27
    相关资源
    最近更新 更多