Django模板-嵌套字典迭代

时间:2020-10-01 08:19:39

标签: python django dictionary django-templates

我的模板从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

我的目标是通过将每种产品的数量和价格相乘,然后与购物车中的每种产品进行加总来计算总计。

有人可能会帮我这个忙,还是至少有助于弄清楚如何正确地通过嵌套字典进行迭代?

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

views.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中写了“总计”的计算 但是,由于产品字典具有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)

2 个答案:

答案 0 :(得分:2)

您可以尝试这样:

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

{{ key }}将为您提供外部字典的键,在您的情况下,20 and 23
{{ key1 }}将为您提供嵌套字典user_id, name,...的密钥
{{ value1 }}将为您带来嵌套字典的价值。

希望它可以提供帮助

答案 1 :(得分:1)

我建议您在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)