Django中的弹性分页 [英] Flexible pagination in Django
问题描述
我想实现分页,这样我可以允许用户选择每页的记录数,例如10,25,50等。我该怎么做?有一个应用程序可以添加到我的项目中吗?
I'd like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project to do this?
谢谢
推荐答案
Django内置了一个Paginator对象。这是一个非常简单的API使用。使用两个参数实例化一个 Paginator
类:列表和每个页面的条目数。我将在底部粘贴一些示例代码。
Django has a Paginator object built into core. It's a rather straightforward API to use. Instantiate a Paginator
class with two arguments: the list and the number of entries per "page". I'll paste some sample code at the bottom.
在您的情况下,您希望允许用户选择每页计数。您可以将每页计数作为URL的一部分(即,您的/ page / 10 /),也可以使其成为查询字符串(即/ your / page /?p = 10)。
In your case you want to allow the user to choose the per-page count. You could either make the per-page count part of the URL (ie. your/page/10/) or you could make it a query string (ie. your/page/?p=10).
某些东西...
# Assuming you're reading the Query String value ?p=
try:
per_page = int(request.REQUEST['p'])
except:
per_page = 25 # default value
paginator = Paginator(objects, per_page)
以下是Django文档页面中的一些示例代码,供Paginator更好地查看如何运作。
Here's some sample code from the Django doc page for the Paginator to better see how it works.
>>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)
>>> p.count
4
>>> p.num_pages
2
>>> p.page_range
[1, 2]
>>> page1 = p.page(1)
>>> page1
<Page 1 of 2>
>>> page1.object_list
['john', 'paul']
这篇关于Django中的弹性分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!