【发布时间】: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