You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据传入ID从字典获取商品?代码报错求助

问题解决:根据ID从字典列表中获取商品并添加到购物车

你遇到的错误翻译为:列表索引必须是整数或切片,不能是字符串

错误原因

你的代码中mes_produits = dico['produits']获取到的是一个列表(值被[]包裹),但你后续尝试用mes_produits['id']来操作——列表只能用整数索引(比如mes_produits[0])访问元素,不能用字符串作为索引,这就是报错的根源。

正确实现方式

要根据传入的id获取对应商品,需要遍历列表中的每个字典元素,匹配id值:

def cart_add(request, id):
    dico = {"produits": [{'id':1,'name':'pomme de terre','price':1250}]}
    mes_produits = dico['produits']
    cart = Cart(request)
    
    # 遍历列表,找到id匹配的商品
    target_product = None
    for product in mes_produits:
        if product['id'] == id:
            target_product = product
            break
    
    # 也可以用更简洁的生成器表达式获取
    # target_product = next((p for p in mes_produits if p['id'] == id), None)
    
    # 确认找到商品后再添加到购物车
    if target_product:
        cart.add(product=target_product)
    
    return render(request, 'cart/cart_detail.html')

关键说明

  1. 遍历mes_produits列表中的每个商品字典,对比字典的id值与传入的参数id
  2. 找到匹配的商品后,再调用cart.add()方法添加
  3. 加入if target_product的判断,避免因未找到商品导致后续报错

内容的提问来源于stack exchange,提问作者Khalifa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:51:20