Django 提供了高级和低级的方法来帮助你管理分页数据——也就是说,数据被分割在几个页面上,并带有“上一页/下一页”链接。
Give Paginator
a list of objects, plus the
number of items you'd like to have on each page, and it gives you methods for
accessing the items for each page:
>>> from django.core.paginator import Paginator
>>> objects = ["john", "paul", "george", "ringo"]
>>> p = Paginator(objects, 2)
>>> p.count
4
>>> p.num_pages
2
>>> type(p.page_range)
<class 'range_iterator'>
>>> p.page_range
range(1, 3)
>>> page1 = p.page(1)
>>> page1
<Page 1 of 2>
>>> page1.object_list
['john', 'paul']
>>> page2 = p.page(2)
>>> page2.object_list
['george', 'ringo']
>>> page2.has_next()
False
>>> page2.has_previous()
True
>>> page2.has_other_pages()
True
>>> page2.next_page_number()
Traceback (most recent call last):
...
EmptyPage: That page contains no results
>>> page2.previous_page_number()
1
>>> page2.start_index() # The 1-based index of the first item on this page
3
>>> page2.end_index() # The 1-based index of the last item on this page
4
>>> p.page(0)
Traceback (most recent call last):
...
EmptyPage: That page number is less than 1
>>> p.page(3)
Traceback (most recent call last):
...
EmptyPage: That page contains no results
备注
请注意,你可以给 Paginator
一个列表/元组,一个 Django 的 QuerySet
,或者任何其它具有 count()
或 __len__()
方法的对象。在确定传递的对象中包含的对象数时,Paginator
将首先尝试调用 count()
,如果传入的对象没有 count()
方法则回退到使用 len()
。这允许像 Django 的 QuerySet
之类的对象在可用的情况下使用更高效的 count()
方法。
ListView
分页¶django.views.generic.list.ListView
提供了一种内置的方式来对显示的列表进行分页。你可以通过在你的视图类中添加:paginate_by
属性来实现此目的,例如:
from django.views.generic import ListView
from myapp.models import Contact
class ContactListView(ListView):
paginate_by = 2
model = Contact
这限制了每页的对象数量,并在 context
中添加了 paginator
和 page_obj
。要允许用户在页面之间导航,请在模板中添加指向下一页和上一页的链接,如下所示:
{% for contact in page_obj %}
{# Each "contact" is a Contact model object. #}
{{ contact.full_name|upper }}<br>
...
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
<a href="?page={{ page_obj.paginator.num_pages }}">last »</a>
{% endif %}
</span>
</div>
Paginator
¶下面是在视图函数中使用 Paginator
对查询结果集分页的例子:
from django.core.paginator import Paginator
from django.shortcuts import render
from myapp.models import Contact
def listing(request):
contact_list = Contact.objects.all()
paginator = Paginator(contact_list, 25) # Show 25 contacts per page.
page_number = request.GET.get("page")
page_obj = paginator.get_page(page_number)
return render(request, "list.html", {"page_obj": page_obj})
在模板 list.html
中,你可以像上面 ListView
的模板一样,在页面之间加入导航。
5月 12, 2023