Django CBV查询商品详情报cannot unpack non-iterable ModelBase错误
错误原因
- 触发
TypeError: cannot unpack non-iterable ModelBase object的直接原因是你在视图里调用ORM的get()方法时传了多余的模型类参数:
你写的Item.objects.get(Item, pk=products_id),因为你已经是通过Item.objects(Item模型的管理器)调用方法,不需要再把Item作为第一个参数传入,get()方法会把传入的非关键字参数当成过滤条件元组尝试解析,就会尝试拆分Item这个模型类对象,触发报错。 - 除了视图的错误,你的模板里也有参数错误:跳转详情的url标签里传入的
products_id没有定义,循环里的单个商品对象是products,应该传入products.id作为参数。 - 潜在问题:你商品列表和商品详情共用同一个
products.html模板,但是两个视图传入的上下文变量名不一样,详情页没有subcategory_list变量,会导致详情页打开后没有内容渲染。
解决方案
1. 修正商品详情视图
把Product_detail类的get方法修改如下,同时建议用get_object_or_404包裹查询,避免商品ID不存在时直接抛出500错误:
# 商品详情视图 class Product_detail(View): def get(self, request, products_id): # 去掉多余的Item参数,改用get_object_or_404处理不存在的场景 item = get_object_or_404(Item, pk=products_id) category_list = Categories.objects.all() return render (request, 'products.html',{"item_list" : item, 'category_list': category_list })
2. 修正模板里的详情跳转链接
把模板里的a标签href部分修改,传入正确的商品ID参数:
<a class="products" href="{% url 'products:detail' products.id %}">
3. 适配模板渲染逻辑(可选但建议)
因为你列表和详情用同一个模板,需要在模板里加判断区分两种场景,参考修改如下:
{% if subcategory_list %} <!-- 商品列表渲染逻辑 --> <section class="col-10"> {% for products in subcategory_list %} <a class="products" href="{% url 'products:detail' products.id %}"> <div class="card col-4" style="width: 18rem; height:400px"> <img class="img" src="{{ products.first.url }}" alt="" height="300px" width="100%" onmouseover="this.src='{{ products.second.url }}'" onmouseout="this.src='{{ products.first.url }}'" > <div class="detail"> <h4 class="price">{{ products.offered_price|currency}}</h4> <h5>{{products.name}} <br> <span>{{ products.brand_name}}</span> </h5> <p class="rate">Rate: 4.5<i class="fas fa-star"></i></p> <h6>Size:<span> {{products.contain_size}}</span> </h6> </div> </div> </a> {% endfor %} </div> </section> {% elif item_list %} <!-- 商品详情渲染逻辑,可根据需求调整展示字段 --> <section class="col-10"> <h2>{{ item_list.name }}</h2> <div class="row"> <div class="col-6"> <img src="{{ item_list.first.url }}" alt="{{ item_list.name }}" width="100%"> </div> <div class="col-6"> <p>品牌:{{ item_list.brand_name }}</p> <p>售价:{{ item_list.offered_price|currency }}</p> <p>原价:<del>{{ item_list.actual_price|currency }}</del></p> {% if item_list.offer %} <p>优惠:{{ item_list.offer }}%</p> {% endif %} <p>尺码范围:{{ item_list.contain_size }}</p> <p>商品介绍:{{ item_list.about }}</p> </div> </div> </section> {% endif %}
内容的提问来源于stack exchange,提问作者Shreyash mishra
相关产品推荐
相关产品推荐

