Django pagination

Django pagination 小结,参见django documentation

  1. 导入Paginator

    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    
  2. 使用Paginator,建立实例

    def listing(request):
    OBJECTS_TO_SHOW = ['test%d' % x for x in xrange(10)]
    NUM_PER_PAGE = 4
    
    paginator = Paginator(OBEJCTS_TO_SHOW, NUM_PER_PAGE)
    
    page = request.GET.get('page')
    
    try:
        contents = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contents = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contents = paginator.page(paginator.num_pages)
    
  3. 在Template中使用

{% for content in contents %}
    {{ content }}<br />
    ...
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if contacts.has_previous %}
            <a href="?page={{ contents.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ contacts.number }} of {{ contents.paginator.num_pages }}.
        </span>

        {% if contents.has_next %}
            <a href="?page={{ contents.next_page_number }}">next</a>
        {% endif %}
    </span>
</div>
  1. 其他相关属性/方法

Paginator 实例具有的属性方法

Paginator.page(page_num)  # 返回第page_num页的一个Page实例

Paginator.count # 所有要显示的内容的长度
Paginator.num_pages # 所有要显示的内容分成的页码数,即共多少页
Paginator.page_range # 页码范围

Page 实例具有的属性/方法

Page.previous()
Page.next()
Page.has_other_pages()
Page.previous_page_number()
Page.next_page_number()
Page.start_index()
Page.end_index()

Page.object_list  # 在本页中显示的内容
Page.number # 本页页码
Page.paginator # 对应的Paginator实例

你可能感兴趣的:(Django pagination)