Search code examples
djangodjango-pagination

Reversing results for current page (django paginator generic view)


I'm using the standard django paginator in my generic view like this:

def get_context_data(self, **kwargs):
        context = super(ArchivePagedView, self).get_context_data(**kwargs) 
        article_list = Article.published
        #=====================================
        paginator = Paginator(article_list, self.paginate_by)
        page = self.request.GET.get('page')

        try:
            article_list = paginator.page(page)
        except PageNotAnInteger:
            article_list = paginator.page(1)
        except EmptyPage:
            article_list = paginator.page(paginator.num_pages)


        if 'reverse' in self.request.GET:
            article_list = article_list.reverse() #This doesn't work!
        else:
            article_list = article_list.all()

        context['article_list'] = article_list

        return context

As you can see I want to override article_list with the same list, but in reversed direction, if reverse is in the URL in behind the question mark. That information I get by 'reverse' in self.request.GET. But I get an error: AttributeError: 'Page' object has no attribute 'reverse'. How do I reverse this? (I don't want to have duplicated code in my template.)

Before I fixed this by making an extra context variable (context['reverse']) which says whether the list should be reversed or not, and then I used duplicated code like this:

{% if reverse %}
 {% for article in article_list reversed %}
  ... some code
 {% endfor %}
{% else %}
 {% for article in article_list %}
  ... the same code
 {% endfor %}
{% endif %}

I wonder if there was no better solution.


Solution

  • Try this

    article_list.object_list = list(reversed(article_list.object_list))