无法在 django 中解压不可迭代的 ModelBase 对象

Posted

技术标签:

【中文标题】无法在 django 中解压不可迭代的 ModelBase 对象【英文标题】:cannot unpack non-iterable ModelBase object in django 【发布时间】:2021-10-03 09:11:53 【问题描述】:

我想在其 ID 的帮助下查看单个项目列表,但无法实现我正在使用 cbv 它向我显示上述错误我正在创建一个电子商务网站,我只想加载该项目详细信息他从所有项目中单击但无法向我显示上述错误

我的模型.py

class Item(models.Model):

    categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_items')
    subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products')
    can_buy = models.ForeignKey(For, on_delete=models.CASCADE, related_name='for_wearing')
    name = models.CharField(max_length=200, blank=False)
    contain_size = models.CharField(max_length=50, blank=True)
    brand_name = models.CharField(max_length=100, blank=False, default='Bagh')
    first = models.ImageField(upload_to='items', blank=False)
    second = models.ImageField(upload_to='items', blank=False)
    third = models.ImageField(upload_to='items', blank=True)
    fourth = models.ImageField(upload_to='items', blank=True)
    fifth = models.ImageField(upload_to='items', blank=True)
    item_vedio = models.FileField(upload_to='item_vedio', blank=True)
    offered_price = models.FloatField(blank=False,)
    actual_price = models.FloatField(blank=False)
    about = models.TextField(blank=False, default="about" )
    offer = models.CharField(max_length=4, blank=True)
    
    def __str__(self):
        return self.name

这是我的意见.py

class Product_detail(View):
    def get(self, request, products_id):
        item = Item.objects.get(Item, pk=products_id)
        category_list = Categories.objects.all()
        print(item)
        return render (request, 'products.html',"item_list" : item, 'category_list': category_list )

我的 urls.py

path('<int:products_id>/details',Product_detail.as_view(),name='detail')

我的href标签

<a href="% url 'products:detail' products.id %">

任何建议都将不胜感激,感谢您的宝贵时间

显示所有项目的 html 视图

class Product(View):
    def get(self, request, subcategory_id):
        subcategory = get_object_or_404(Subcategories, pk=subcategory_id)
        products = subcategory.products.all()
        category_list = Categories.objects.all()
        print(products)
        return render (request, 'products.html',"subcategory_list" : products, 'category_list': category_list )

我猜你需要那个

添加产品.html

<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 "    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>

我的产品网址

path('<int:subcategory_id>/products/',Product.as_view(),name='product'),

添加回溯

Environment:


Request Method: GET
Request URL: http://localhost:8000/1/details

Django Version: 3.2.5
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'crispy_forms',
 'accounts',
 'products']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\coolbuy\products\views.py", line 29, in get
    item = Item.objects.get(Item, pk=item_id)
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\db\models\query.py", line 424, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\db\models\query.py", line 941, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\db\models\query.py", line 961, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\db\models\query.py", line 968, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\db\models\sql\query.py", line 1393, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\db\models\sql\query.py", line 1412, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\mithlesh\Desktop\coolbuy 2.0\lib\site-packages\django\db\models\sql\query.py", line 1283, in build_filter
    arg, value = filter_expr

Exception Type: TypeError at /1/details
Exception Value: cannot unpack non-iterable ModelBase object

【问题讨论】:

你能分享整个追溯吗?还有"item_list" : item,这里的item只是一个例子,你是用这个作为你模板中的列表吗? @bdbd 我刚刚添加实际上我将我的子类别与项目链接,所以当我点击任何特定的子类别时,products.html 将打开与该子类别相关的项目列表,所以我想实现任何一次单击该子类别的任何项目,然后 products.detail 打开并且仅显示与该项目相关的内容 @bdbd 抱歉,使用它作为列表是错字,我只想要该页面上的项目详细信息而不是列表 回溯告诉你这一行的确切问题:Item.objects.get(Item, pk=item_id)。尝试先解决这个问题 我成功了,顺便谢谢你 【参考方案1】:

你的 URLs href 的问题

你可以这样试试:

<a href="% url 'products:detail' products_id=products.id %">

【讨论】:

添加了我的产品视图,显示所有项目

以上是关于无法在 django 中解压不可迭代的 ModelBase 对象的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:无法在 Django REST 框架中解压不可迭代的 int 对象

PyAutoGui TypeError:无法解压不可迭代的 NoneType 对象

使用python字典时无法解压不可迭代的int对象

Django'logout'TypeError:'AnonymousUser'对象不可迭代

Django迭代多个对象

TypeError:'BasePermissionMetaclass' 对象在 django rest 框架中不可迭代