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

Django类视图get_queryset分页报错,寻求解决方案

Django ListView分类分页问题解决

问题原因

你的代码存在两个核心问题导致报错:

  1. get_queryset返回值不符合要求:ListView要求该方法返回可切片的可迭代对象(如Django QuerySet、列表),但你返回了字典。分页组件尝试对字典执行切片操作时,字典不支持该操作,因此抛出unhashable type: 'slice'错误。
  2. 语法错误:paginate_by 12缺少赋值等号,正确写法应为paginate_by = 12。

修正方案

正确重写get_queryset与添加额外上下文

修改views.py代码如下:

class CatListView(ListView):
    template_name = 'category.html'
    context_object_name = 'posts'  # 对应模板中遍历的文章集合
    paginate_by = 12  # 修复语法错误,设置每页展示12条数据

    def get_queryset(self):
        # 直接返回过滤后的Post QuerySet,满足ListView分页所需的可迭代对象要求
        return Post.objects.filter(
            category__name=self.kwargs['category'],
            status='published'
        )
    
    def get_context_data(self, **kwargs):
        # 通过get_context_data将分类名称传入模板上下文
        context = super().get_context_data(**kwargs)
        context['cat'] = self.kwargs['category']
        return context

模板无需修改

你的分页模板代码逻辑正确,ListView会自动将分页相关变量(page_obj、paginator、is_paginated)传入模板,直接保留原代码即可。

简化实现思路

如果觉得重写方法繁琐,也可以基于基础属性配置,仅在必要时重写方法:

class CatListView(ListView):
    template_name = 'category.html'
    model = Post
    context_object_name = 'posts'
    paginate_by = 12

    def get_queryset(self):
        # 基于父类的queryset进行过滤,仅返回符合条件的数据
        return super().get_queryset().filter(
            category__name=self.kwargs['category'],
            status='published'
        )
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['cat'] = self.kwargs['category']
        return context

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:50:25