Search code examples
pythondjangolistviewsearchpaginator

changeing ListView get_queryset? pagination in django


Good day everyone. I am having some trouble with the paginator in django. I have in my db all the customers info, so what I want to do is to display that info, but I made a search function in which you clic a letter button, for example you clic A and it will filter all the customers that their last name starts with the letter A, if you clic B , it will filter all customers with their last name start with B, and so on. This works correctly, the problem is that I also want to display 10 customers per page, so if I have 20 customers that their last name starts with the letter A, what you will see, will be 10 customers and a bar that says ( <<< page 1 page 2 >>> ) or something like that, and that should be solved with the paginator, I added it, but its not working. I think the problem is that maybe my get function is rewriting the get_query function from ListView perhaps? I tryed different things but I'm not sure. Here is my code in views:

class ExpedientView(ListView):
    queryset = Portfolio.objects.filter(products__isnull=True).order_by('owner__last_name')
    template_name = 'dashboard-admin/portfoliorecords.html'
    paginate_by = 10

    def get(self,request):
        if request.GET['letter'] == '':
            context_object_name = 'portfolios'
            queryset = Portfolio.objects.filter(products__isnull=True).order_by('owner__last_name')
            context = queryset
        else:
            letter = request.GET['letter']
            context_object_name = 'portfolios'
            queryset = Portfolio.objects.filter(products__isnull=True).order_by('owner__last_name').filter(owner__last_name__istartswith=letter)
            context = queryset
        return render(request, 'dashboard-admin/portfoliorecords.html', {'portfolios': context})

the get(self,request) function, works perfectly, however the first part where the paginated_by is not working.

Before I added the get function, and just filtering all the customers, the paginator worked fine, so in the template, the code works properly.


Solution

  • You have to modify the def get_queryset(self) method not the def get(self, request) method

    Remove the def get(self, request) method and the below code.

    def get_queryset(self):
        queryset = Portfolio.objects.filter(products__isnull=True).order_by('owner__last_name')
        letter = request.GET.get('letter', None)
        if letter:
            queryset.filter(owner__last_name__istartswith=letter)
        return queryset