【问题标题】:Django Template - Nested Dictionary IterationDjango 模板 - 嵌套字典迭代
【发布时间】:2021-01-16 22:45:39
【问题描述】:

我的模板根据购物车内容的嵌套字典从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

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

有人可以帮我解决这个问题,或者至少帮助弄清楚如何正确地遍历嵌套字典吗?

我正在为购物车使用以下库: 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 个属性,因此对于购物车中的每个产品,“总计”在循环中添加了 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)

【问题讨论】:

  • 也显示你的views.py
  • 更新原帖
  • 其实我的意思是说 total_price = total_price + (float(value['quantity']) * float(value['price'])) 进入第一个循环,但在第二个循环之外。

标签: python django dictionary django-templates


【解决方案1】:

你可以这样试试:

{% 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 }} 会给你的值嵌套字典。

希望对你有帮助

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 感谢您的建议!我已经尝试过了,它对我很有用,请查看更新后的帖子以获取详细信息。
    • 其实我的意思是说 total_price = total_price + (float(value['quantity']) * float(value['price'])) 进入第一个循环,但在第二个循环之外。
    • 我更新了我的答案。如果它解决了您的问题,请将其标记为正确。
    猜你喜欢
    • 2014-08-19
    • 2012-07-27
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多