首页 > 解决方案 > Django CBV (ListView) paginate_by not allowed with queryset

问题描述

I'm trying to paginate my tasks but I can't

views.py:

class DashboardTaskAppView(LoginRequiredMixin, ListView):
    model = Task
    template_name = "task_app/task_dashboard.html"
    context_object_name = 'tasks'
    today = datetime.date.today()
    paginate_by = 5
    
    def queryset(self):
        ordering = ['-due_date']
        usr = self.request.user
        return Task.objects.filter(Q(responsable=usr))

Without paginate_by = 5: working dashboard, all objects render

WITH paginate_by = 5:

TypeError at /task/
object of type 'method' has no len()
Request Method: GET
Request URL:    http://localhost:8000/task/
Django Version: 3.1.2
Exception Type: TypeError
Exception Value:    
object of type 'method' has no len()
Exception Location: C:\Users\caior\Desktop\Python\simple_task\venv\lib\site-packages\django\core\paginator.py, line 95, in count
Python Executable:  C:\Users\caior\Desktop\Python\simple_task\venv\Scripts\python.exe
Python Version: 3.8.5
Python Path:    
['C:\\*\\*\\*\\Python\\simple_task',
 'C:\\*\\*\\*\\Python\\simple_task\\venv\\Scripts\\python38.zip',
 'c:\\*\\*\\*\\local\\programs\\python\\python38-32\\DLLs',
 'c:\\*\\*\\*\\local\\programs\\python\\python38-32\\lib',
 'c:\\*\\*\\*\\local\\programs\\python\\python38-32',
 'C:\\*\\*\\*\\Python\\simple_task\\venv',
 'C:\\*\\*\\*\\Python\\simple_task\\venv\\lib\\site-packages']
Server time:    Mon, 09 Nov 2020 09:48:07 +0100

Console:

  File "C:\*\*\*\Python\simple_task\venv\lib\site-packages\django\core\paginator.py", line 95, in count
    return len(self.object_list)
TypeError: object of type 'method' has no len()
[09/Nov/2020 09:48:07] "GET /task/ HTTP/1.1" 500 112987


Any help is appreciated, thanks a lot in advance, Kind regards

标签: djangodjango-pagination

解决方案


You are overriding queryset attribute of the View with a method. Instead, you should override get_queryset method:

class DashboardTaskAppView(LoginRequiredMixin, ListView):
    # rest of the code

    def get_queryset(self):
        ordering = ['-due_date']
        usr = self.request.user
        return Task.objects.filter(Q(responsable=usr))

推荐阅读