Search code examples
djangodjango-viewsdjango-pagination

how to paginate and sort multiple querysets in same page?


I am using two query sets in one page and I want to have different paginations for each one

this is my class based view:

class MainListView(ListView):
    queryset = Post.objects.all()
    template_name = 'main.html'
    context_object_name = 'posts'

    def get_context_data(self, **kwargs):
        context = super(MainListView, self).get_context_data(**kwargs)
        context['news'] = EventsPost.objects.all()
        context['posts'] = self.queryset
        return context

I want the Post model to be paginated by 3 and EventsPost by 6 Thanks for your responses


Solution

  • Since you don't need pagination, I would use a TemplateView, and add the two querysets to the context in the get_context_data method.

    class MainListView(TemplateView):
    
        def get_context_data(self, **kwargs):
            context = super(MainListView, self).get_context_data(**kwargs)
            context['news'] = EventsPost.objects.order_by('-pk')[:6]
            context['posts'] = Post.objects.order_by('-pk')[:3]
            return context
    

    If you want to sort on a different field, you could change it to something else e.g. order_by('-date')