pagination.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. ==========
  2. Pagination
  3. ==========
  4. .. module:: django.core.paginator
  5. :synopsis: Classes to help you easily manage paginated data.
  6. Django provides a few classes that help you manage paginated data -- that is,
  7. data that's split across several pages, with "Previous/Next" links. These
  8. classes live in :file:`django/core/paginator.py`.
  9. Example
  10. =======
  11. Give :class:`Paginator` a list of objects, plus the number of items you'd like to
  12. have on each page, and it gives you methods for accessing the items for each
  13. page::
  14. >>> from django.core.paginator import Paginator
  15. >>> objects = ['john', 'paul', 'george', 'ringo']
  16. >>> p = Paginator(objects, 2)
  17. >>> p.count
  18. 4
  19. >>> p.num_pages
  20. 2
  21. >>> type(p.page_range)
  22. <class 'range_iterator'>
  23. >>> p.page_range
  24. range(1, 3)
  25. >>> page1 = p.page(1)
  26. >>> page1
  27. <Page 1 of 2>
  28. >>> page1.object_list
  29. ['john', 'paul']
  30. >>> page2 = p.page(2)
  31. >>> page2.object_list
  32. ['george', 'ringo']
  33. >>> page2.has_next()
  34. False
  35. >>> page2.has_previous()
  36. True
  37. >>> page2.has_other_pages()
  38. True
  39. >>> page2.next_page_number()
  40. Traceback (most recent call last):
  41. ...
  42. EmptyPage: That page contains no results
  43. >>> page2.previous_page_number()
  44. 1
  45. >>> page2.start_index() # The 1-based index of the first item on this page
  46. 3
  47. >>> page2.end_index() # The 1-based index of the last item on this page
  48. 4
  49. >>> p.page(0)
  50. Traceback (most recent call last):
  51. ...
  52. EmptyPage: That page number is less than 1
  53. >>> p.page(3)
  54. Traceback (most recent call last):
  55. ...
  56. EmptyPage: That page contains no results
  57. .. note::
  58. Note that you can give ``Paginator`` a list/tuple, a Django ``QuerySet``,
  59. or any other object with a ``count()`` or ``__len__()`` method. When
  60. determining the number of objects contained in the passed object,
  61. ``Paginator`` will first try calling ``count()``, then fallback to using
  62. ``len()`` if the passed object has no ``count()`` method. This allows
  63. objects such as Django's ``QuerySet`` to use a more efficient ``count()``
  64. method when available.
  65. Paginating a ``ListView``
  66. =========================
  67. :class:`django.views.generic.list.ListView` provides a builtin way to paginate
  68. the displayed list. You can do this by adding
  69. :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_by` attribute to
  70. your view class, for example::
  71. from django.views.generic import ListView
  72. from myapp.models import Contacts
  73. class ContactsList(ListView):
  74. paginate_by = 2
  75. model = Contacts
  76. The only thing your users will be missing is a way to navigate to the next or
  77. previous page. To achieve this, add links to the next and previous page, like
  78. shown in the below example ``list.html``.
  79. .. _using-paginator-in-view:
  80. Using ``Paginator`` in a view
  81. =============================
  82. Here's a slightly more complex example using :class:`Paginator` in a view to
  83. paginate a queryset. We give both the view and the accompanying template to
  84. show how you can display the results. This example assumes you have a
  85. ``Contacts`` model that has already been imported.
  86. The view function looks like this::
  87. from django.core.paginator import Paginator
  88. from django.shortcuts import render
  89. def listing(request):
  90. contact_list = Contacts.objects.all()
  91. paginator = Paginator(contact_list, 25) # Show 25 contacts per page
  92. page = request.GET.get('page')
  93. contacts = paginator.get_page(page)
  94. return render(request, 'list.html', {'contacts': contacts})
  95. In the template :file:`list.html`, you'll want to include navigation between
  96. pages along with any interesting information from the objects themselves:
  97. .. code-block:: html+django
  98. {% for contact in contacts %}
  99. {# Each "contact" is a Contact model object. #}
  100. {{ contact.full_name|upper }}<br>
  101. ...
  102. {% endfor %}
  103. <div class="pagination">
  104. <span class="step-links">
  105. {% if contacts.has_previous %}
  106. <a href="?page=1">&laquo; first</a>
  107. <a href="?page={{ contacts.previous_page_number }}">previous</a>
  108. {% endif %}
  109. <span class="current">
  110. Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
  111. </span>
  112. {% if contacts.has_next %}
  113. <a href="?page={{ contacts.next_page_number }}">next</a>
  114. <a href="?page={{ contacts.paginator.num_pages }}">last &raquo;</a>
  115. {% endif %}
  116. </span>
  117. </div>
  118. ``Paginator`` objects
  119. =====================
  120. The :class:`Paginator` class has this constructor:
  121. .. class:: Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)
  122. Required arguments
  123. ------------------
  124. ``object_list``
  125. A list, tuple, ``QuerySet``, or other sliceable object with a ``count()``
  126. or ``__len__()`` method. For consistent pagination, ``QuerySet``\s should
  127. be ordered, e.g. with an :meth:`~django.db.models.query.QuerySet.order_by`
  128. clause or with a default :attr:`~django.db.models.Options.ordering` on the
  129. model.
  130. .. admonition:: Performance issues paginating large ``QuerySet``\s
  131. If you're using a ``QuerySet`` with a very large number of items,
  132. requesting high page numbers might be slow on some databases, because
  133. the resulting ``LIMIT``/``OFFSET`` query needs to count the number of
  134. ``OFFSET`` records which takes longer as the page number gets higher.
  135. ``per_page``
  136. The maximum number of items to include on a page, not including orphans
  137. (see the ``orphans`` optional argument below).
  138. Optional arguments
  139. ------------------
  140. ``orphans``
  141. Use this when you don't want to have a last page with very few items.
  142. If the last page would normally have a number of items less than or equal
  143. to ``orphans``, then those items will be added to the previous page (which
  144. becomes the last page) instead of leaving the items on a page by
  145. themselves. For example, with 23 items, ``per_page=10``, and
  146. ``orphans=3``, there will be two pages; the first page with 10 items and
  147. the second (and last) page with 13 items. ``orphans`` defaults to zero,
  148. which means pages are never combined and the last page may have one item.
  149. ``allow_empty_first_page``
  150. Whether or not the first page is allowed to be empty. If ``False`` and
  151. ``object_list`` is empty, then an ``EmptyPage`` error will be raised.
  152. Methods
  153. -------
  154. .. method:: Paginator.get_page(number)
  155. Returns a :class:`Page` object with the given 1-based index, while also
  156. handling out of range and invalid page numbers.
  157. If the page isn't a number, it returns the first page. If the page number
  158. is negative or greater than the number of pages, it returns the last page.
  159. It raises an exception (:exc:`EmptyPage`) only if you specify
  160. ``Paginator(..., allow_empty_first_page=False)`` and the ``object_list`` is
  161. empty.
  162. .. method:: Paginator.page(number)
  163. Returns a :class:`Page` object with the given 1-based index. Raises
  164. :exc:`InvalidPage` if the given page number doesn't exist.
  165. Attributes
  166. ----------
  167. .. attribute:: Paginator.count
  168. The total number of objects, across all pages.
  169. .. note::
  170. When determining the number of objects contained in ``object_list``,
  171. ``Paginator`` will first try calling ``object_list.count()``. If
  172. ``object_list`` has no ``count()`` method, then ``Paginator`` will
  173. fallback to using ``len(object_list)``. This allows objects, such as
  174. Django's ``QuerySet``, to use a more efficient ``count()`` method when
  175. available.
  176. .. attribute:: Paginator.num_pages
  177. The total number of pages.
  178. .. attribute:: Paginator.page_range
  179. A 1-based range iterator of page numbers, e.g. yielding ``[1, 2, 3, 4]``.
  180. ``InvalidPage`` exceptions
  181. ==========================
  182. .. exception:: InvalidPage
  183. A base class for exceptions raised when a paginator is passed an invalid
  184. page number.
  185. The :meth:`Paginator.page` method raises an exception if the requested page is
  186. invalid (i.e., not an integer) or contains no objects. Generally, it's enough
  187. to catch the ``InvalidPage`` exception, but if you'd like more granularity,
  188. you can catch either of the following exceptions:
  189. .. exception:: PageNotAnInteger
  190. Raised when ``page()`` is given a value that isn't an integer.
  191. .. exception:: EmptyPage
  192. Raised when ``page()`` is given a valid value but no objects exist on that
  193. page.
  194. Both of the exceptions are subclasses of :exc:`InvalidPage`, so you can handle
  195. them both with a simple ``except InvalidPage``.
  196. ``Page`` objects
  197. ================
  198. You usually won't construct ``Page`` objects by hand -- you'll get them
  199. using :meth:`Paginator.page`.
  200. .. class:: Page(object_list, number, paginator)
  201. A page acts like a sequence of :attr:`Page.object_list` when using
  202. ``len()`` or iterating it directly.
  203. Methods
  204. -------
  205. .. method:: Page.has_next()
  206. Returns ``True`` if there's a next page.
  207. .. method:: Page.has_previous()
  208. Returns ``True`` if there's a previous page.
  209. .. method:: Page.has_other_pages()
  210. Returns ``True`` if there's a next *or* previous page.
  211. .. method:: Page.next_page_number()
  212. Returns the next page number. Raises :exc:`InvalidPage` if next page
  213. doesn't exist.
  214. .. method:: Page.previous_page_number()
  215. Returns the previous page number. Raises :exc:`InvalidPage` if previous
  216. page doesn't exist.
  217. .. method:: Page.start_index()
  218. Returns the 1-based index of the first object on the page, relative to all
  219. of the objects in the paginator's list. For example, when paginating a list
  220. of 5 objects with 2 objects per page, the second page's
  221. :meth:`~Page.start_index` would return ``3``.
  222. .. method:: Page.end_index()
  223. Returns the 1-based index of the last object on the page, relative to all
  224. of the objects in the paginator's list. For example, when paginating a list
  225. of 5 objects with 2 objects per page, the second page's
  226. :meth:`~Page.end_index` would return ``4``.
  227. Attributes
  228. ----------
  229. .. attribute:: Page.object_list
  230. The list of objects on this page.
  231. .. attribute:: Page.number
  232. The 1-based page number for this page.
  233. .. attribute:: Page.paginator
  234. The associated :class:`Paginator` object.