jondykeman
jondykeman

Reputation: 6272

Paginate search results ListView

I am using ListView to display all of the NewPersons and paginate by 5 results. NewPersons are displayed in a table and on the left there is a search box. When searching 'q' is requested in the GET. In order to change the queryset when searching I have overridden the get_queryset method of the view.

The problem I am having is that because I am paginating by 5 results if more than 5 results are returned by the search they are paginated; however, if you click next to view the second page it returns the second page of the full list of objects not the second page of the search results.

So I am wondering how to properly paginate my search results. Thanks. JD

class PersonListView(ListView):
model = NewPerson
template_name = 'list.html' 
paginate_by = 5

def get_queryset(self):
    """
    Get the list of items for this view. This must be an interable, and may
    be a queryset (in which qs-specific behavior will be enabled).
    """
    if 'q' in self.request.GET:
        q = self.request.GET['q']
        queryset = NewPerson.objects.filter(Q(FirstName__icontains=q) | Q(LastName__icontains=q))
    else:
        if self.queryset is not None:
            queryset = self.queryset
            if hasattr(queryset, '_clone'):
                queryset = queryset._clone()
        elif self.model is not None:
            queryset = self.model._default_manager.all()
        else:
            raise ImproperlyConfigured(u"'%s' must define 'queryset' or 'model'"
                                       % self.__class__.__name__)
    return queryset

Upvotes: 2

Views: 2829

Answers (2)

Waqas
Waqas

Reputation: 639

Or if you have multiple search terms

 <a href="?{{ request.GET.urlencode }}&page={{ page_obj.next_page_number }}">
Next&nbsp;&raquo;
</a>

Upvotes: 3

idevmad
idevmad

Reputation: 51

Add to you ListView's template something like this:

{% if request.GET.q %}

<a href="?search={{ request.GET.search}}&page={{ page_obj.next_page_number }}">
Next&nbsp;&raquo;
</a>

{% else %}

<a href="?page={{ page_obj.next_page_number }}">Next&nbsp;&raquo;</a>

{% endif %}

Upvotes: 5

Related Questions