Django:无法解包不可迭代的Posts对象(TypeError)

时间:2020-08-03 15:22:19

标签: python django django-models django-views

我正在尝试通过其中一个属性来过滤“帖子”模型中存在的元素。

这是我基于班级的视图:

class FilteredPostListView(ListView):
model = Posts
template_name = "blog/post-category.html"
context_object_name = "posts"
paginate_by = 6

#the actual fuction that should filter the element by their category attribute: 
def get_queryset(self):
    category = get_object_or_404(Posts, category=self.kwargs.get("category")) 
    return Posts.objects.filter(category)

这是我urls.py中的相关代码段:

path('category/<category>/', FilteredPostListView.as_view(), name='category')

当我输入URL localhost:8000 / category / example /,其中“ example”是我要过滤的“ category”属性的值时,出现以下错误:

如果多个Posts对象的属性类别的值为“ example”:

MultipleObjectsReturned at /category/example/
get() returned more than one Posts -- it returned 2!

如果只有一个Posts对象具有值为“ example”的属性类别:

TypeError at /category/example/
cannot unpack non-iterable Posts object

为什么返回不可迭代的对象?

更新:

如果将def get_queryset()方法更改为更简化的版本,并且将属性“ category”的值硬编码为这种形式:

    def get_queryset(self):
        return Posts.objects.filter(category="example")

然后,代码可以完美运行,并且基于类的视图返回可迭代对象,这些对象的属性“ category”设置为“ example”,并且可以使用for代码块显示在模板中。

但是,每当我想通过属性过滤“帖子”对象时,我都无法对属性“类别”的值进行硬编码。

所以问题出在方法的更复杂的版本上:

    def get_queryset(self):
        category = self.kwargs.get("category")
        return Posts.objects.filter(category).order_by("-date_posted")

由于某种原因,它返回了不可迭代的对象。

0 个答案:

没有答案