Search code examples
djangodjango-class-based-viewsdjango-pagination

Django CBV ListView, accessing both paginated and unpaginated results


I built a list view using generic view class ListView with pagination and search functionality. Now I want to include in the same page a map with markers for all the results, without pagination.

Is there a way to reach both paginated and unpaginated results without having to do a duplicate query?


Solution

  • We can do it by override the method def get_context_data(self, **kwargs). It takes only a single query.

    class MyListview(ListView):
    
        def get_context_data(self, **kwargs):
            kwargs['obj_list'] = list(kwargs['obj_list'])
            my_obj_list = kwargs['obj_list']
            context = super(MyListview, self).get_context_data(**kwargs)
            context['my_obj_list'] = my_obj_list
            return context