Django pagination and “current page”

后端 未结 3 801
旧时难觅i
旧时难觅i 2021-02-07 13:16

I\'m currently developing a Django application which will make use of the infamous \"pagination\" technique. I\'m trying to figure out how the django.core.paginator module work

3条回答
  •  梦毁少年i
    2021-02-07 13:56

    Hmm... I see from your comment that you don't want to do the ol' GET parameter, which is what django.core.paginator was written for using. To do what you want, I can think of no better way than to precompute the page that each question is on. As an example, your view will end up being something like:

    ITEMS_PER_PAGE = 20
    def show_question(question_pk):
        questions = Question.objects.all()
        for index, question in enumerate(questions):
            question.page = ((index - 1) / ITEMS_PER_PAGE) + 1
        paginator = Paginator(questions, ITEMS_PER_PAGE)
        page = paginator.page(questions.get(pk=question_pk).page)
        return render_to_response('show_question.html', { 'page' : page })
    

    To highlight the current page in the template, you'd do something like

    {% for i in page.paginator.page_range %}
        {% ifequal i page.number %}
            
        {% else %}
            
        {% endifequal %}
    {% endfor %}
    

    As for the items, you'll have two different object_lists to work with...

    page.object_list
    

    will be the objects in the current page and

    page.paginator.object_list
    

    will be all objects, regardless of page. Each of those items will have a "page" variable that will tell you which page they're on.

    That all said, what you're doing sounds unconventional. You may want to rethink, but either way, good luck.

提交回复
热议问题