Django模板嵌套字典迭代

2024-05-10 07:35:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我的模板从views.py接收以下购物车内容的嵌套字典

{
'20': 
    {'userid': 1, 
    'product_id': 20, 
    'name': 'Venus de Milos', 
    'quantity': 1, 
    'price': '1500.00', 
    'image': '/media/static/photos/pngegg.png'}, 
'23': 
    {'userid': 1, 
    'product_id': 23, 
    'name': 'Bicycle', 
    'quantity': 1, 
    'price': '1000.00', 
    'image': '/media/static/photos/366f.png'}
}

我在迭代过程中遇到了问题。 例如,当我使用以下代码时

{% for key, value in list %}

{{ key }} {{ value }}

{% endfor %}

我收到的不是键和值,而是:

2 0 
2 3

我的目标是通过将每种产品的数量和价格相乘,并将其与购物车中的每种产品相加,来计算总金额

sombody可以帮我一把吗,或者至少帮我弄清楚如何正确地遍历嵌套字典

我正在为购物车使用以下库: https://pypi.org/project/django-shopping-cart/

视图。py:

@login_required(login_url="/users/login")
def cart_detail(request):
    cart = Cart(request)
    queryset = cart.cart
    context = {"list": queryset }
    return render(request, 'cart_detail.html', context)

已解决(种类): 按照您的建议,我在views.py中为“total”编写了计算 但是,由于产品字典有6个属性,所以对于购物车中的每个产品,“total”在循环中添加了6次。 现在我刚刚添加了6除法,但显然这不是合理的解决方案

def cart_detail(request):
    cart = Cart(request)
    queryset = cart.cart

    total_price=0

    for key, value in queryset.items():
        for key1, value1 in value.items():
            total_price = total_price + (float(value['quantity']) * float(value['price']))
    #Temporal decision
    total_price = total_price / 6
    
    context = {"list": queryset, "total_price": total_price }
    return render(request, 'cart_detail.html', context)

Tags: keypyfor字典产品valuerequestcontext
2条回答

您可以这样尝试:

{% for key, value in list.items %} <-first loop
   {{ key }}
   {% for key1, value1 in value.items %} <  second loop
      {{ key1 }} - {{ value1 }}
   {% endfor %}
{% endfor %}

{{ key }}将为您提供外部dict的密钥,在您的情况下20 and 23
{{ key1 }}将为您提供嵌套dict的密钥user_id, name,...
{{ value1 }}将为您提供嵌套dict的值

希望能有所帮助

我建议您在views.py中进行计算,将它们保存到变量中,然后将其传递给模板

假设你的

保存在变量cart_dict中:

    total_price=0

    for product in cart_dict:            
        total_price = total_price + (float(product['quantity']) * float(product['price']))
    
    context = {"cart_dict: cart_dict, "total_price": total_price }
    return render(request, 'cart_detail.html', context)
    

相关问题 更多 >