【问题标题】:Django - 'ManyRelatedManager' object is not iterableDjango - 'ManyRelatedManager' 对象不可迭代
【发布时间】:2021-05-03 05:12:49
【问题描述】:

在我的 Django 项目的这个特定部分中,我试图返回一个 dict,其中包含我过滤过的对象的 QuerySet,以便这些对象可以在它们传递到的模板中使用。以下是我的代码:

在views.py中

def shows_in_category(request, category_slug):
 category = get_object_or_404(Category, slug=category_slug)
 print(category_slug)
 shows = theShow.objects.filter(category__name=category).all()
 print(shows)
 return render(request, 'show/show_list_view.html', {'shows': shows})

在 models.py 中

class Category(models.Model):
 name = models.CharField(max_length=255, db_index=True)
 slug = models.SlugField(max_length=255, unique=True)


 class Meta:
  verbose_name_plural = 'Categories'

 def __str__(self):
  return self.name

 def get_absolute_url(self):
  return reverse("theshowapp:shows_in_category", args=[self.slug])

class theShow(models.Model):
 english_name = models.CharField(max_length=400)
 show_type = models.CharField(max_length=200, blank=True)
 category = models.ManyToManyField(Category)
 slug = models.SlugField(max_length=400,unique=True)

 class Meta:
  verbose_name_plural = 'Shows Series'

 def __str__(self):
  return self.english_name

这是完整的回溯:

Traceback (most recent call last):
File "C:\Users\danie\miniconda3\lib\site- 
packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\danie\miniconda3\lib\site- 
packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\danie\OneDrive\Documents\streamingsitetest\showing\views.py", line 
14, in shows_in_category
return render(request, 'show_templates/show_list_view.html', {'shows': 
shows})
File "C:\Users\danie\miniconda3\lib\site-packages\django\shortcuts.py", line 
19, in render
content = loader.render_to_string(template_name, context, request, 
using=using)
File "C:\Users\danie\miniconda3\lib\site- 
packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\danie\miniconda3\lib\site- 
packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\danie\miniconda3\lib\site-packages\django\template\base.py", 
line 170, in render
return self._render(context)
File "C:\Users\danie\miniconda3\lib\site-packages\django\template\base.py", 
line 162, in _render
return self.nodelist.render(context)
File "C:\Users\danie\miniconda3\lib\site-packages\django\template\base.py", 
line 938, in render
bit = node.render_annotated(context)
File "C:\Users\danie\miniconda3\lib\site-packages\django\template\base.py", 
line 905, in render_annotated
return self.render(context)
File "C:\Users\danie\miniconda3\lib\site- 
packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:\Users\danie\miniconda3\lib\site-packages\django\template\base.py", 
line 162, in _render
return self.nodelist.render(context)
File "C:\Users\danie\miniconda3\lib\site-packages\django\template\base.py", 
line 938, in render
bit = node.render_annotated(context)
File "C:\Users\danie\miniconda3\lib\site-packages\django\template\base.py", 
line 905, in render_annotated
return self.render(context)
File "C:\Users\danie\miniconda3\lib\site- 
packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\danie\miniconda3\lib\site-packages\django\template\base.py", 
line 938, in render
bit = node.render_annotated(context)
File "C:\Users\danie\miniconda3\lib\site-packages\django\template\base.py", 
line 905, in render_annotated
return self.render(context)
File "C:\Users\danie\miniconda3\lib\site- 
packages\django\template\defaulttags.py", line 211, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\danie\miniconda3\lib\site-packages\django\template\base.py", 
line 905, in render_annotated
return self.render(context)
File "C:\Users\danie\miniconda3\lib\site- 
packages\django\template\defaulttags.py", line 167, in render
values = list(values)

Exception Type: TypeError at /shows/action
Exception Value: 'ManyRelatedManager' object is not iterable

我从之前与我类似的问题中了解到,我需要将 shows 设为 QuerySet 以便它是可迭代的,这就是我在其定义末尾添加 .all() 的原因。我使用了 print(type(shows)) 并确保创建了一个 QuerySet 并且我仍然收到此错误。我该怎么做才能遍历shows

【问题讨论】:

  • 请发布完整回溯。
  • 那些是对象。你想从这些对象返回什么信息?顺便说一句,你想要的是print(type(shows)),而不是print(shows.type())
  • 也许你想使用shows.show_type() bc 这是变量名?
  • 为什么要打印类别和“类型”?只需注释掉这些行。
  • @bimmui 你的问题和你的标题似乎不匹配顺便说一句。

标签: python django django-models django-queryset


【解决方案1】:

我认为您正在寻找(假设)是在反向关系中使用的 related_name 属性

如果你没有指定related_name,Django 会自动创建一个 例如,使用带有后缀 _set 的模型名称 theshow_set

所以你必须在这里做的是,

class theShow(models.Model):
    category = models.ManyToManyField(Category, related_name='theshow_Set')
    ...

当您查询时,

category = get_object_or_404(Category, slug=category_slug).theshow_set.all()

注意:我认为这是您打算做的。

【讨论】:

    【解决方案2】:

    而不是

    shows = theShow.objects.filter(category__name=category).all()

    我使用这行代码来代替返回字典而不是对象的 QuerySet。

    shows = animeShow.objects.filter(category__name=category).values()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 2021-02-04
      • 2020-02-28
      • 2013-05-07
      • 2019-07-25
      相关资源
      最近更新 更多