Conditional pagination_by number in Django

Viewed 201

I have a Django view with pagination:

class MyListView(ListView):
     model = Model
     context_object_name = "Model"
     template_name = "template.html"
     paginate_by = 6

This template has a search bar that works fine:

def get_queryset(self):
     if query:
          postresult = account_list.filter(name__contains=query)     
          list = postresult  
     return list

The problem is, I want the pagination value for a page with a search query to be 20. How can I make the paginate_by value a conditional?

1 Answers

You can override the get_paginate_by(…) method [Django-doc] instead:

class MyListView(ListView):
    model = Model
    context_object_name = "Model"
    template_name = "template.html"
    paginate_by = 6

    def get_paginate_by(self, queryset):
        query = self.request.GET.get('q')
        if query:
            return 20
        else:
            return super().get_paginate_by(queryset)

The origin of the query parameter in your code is however unknown, so you might have to change the query = … logic.

You can return None in case you do not want to paginate the Queryset (for a certain condition).

Related