簡體   English   中英

Django 模板 - 嵌套字典迭代

[英]Django Template - Nested Dictionary Iteration

我的模板在購物車內容的嵌套字典之后從 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/

視圖.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)

你可以這樣嘗試:

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

希望它可以幫助

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM