paginator.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. =========
  2. Paginator
  3. =========
  4. Django provides a few classes that help you manage paginated data -- that is,
  5. data that's split across several pages, with "Previous/Next" links. These
  6. classes live in :source:`django/core/paginator.py`.
  7. For examples, see the :doc:`Pagination topic guide </topics/pagination>`.
  8. .. module:: django.core.paginator
  9. :synopsis: Classes to help you easily manage paginated data.
  10. ``Paginator`` class
  11. ===================
  12. .. class:: Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True, error_messages=None)
  13. A paginator acts like a sequence of :class:`Page` when using ``len()`` or
  14. iterating it directly.
  15. .. attribute:: Paginator.object_list
  16. Required. A list, tuple, ``QuerySet``, or other sliceable object with a
  17. ``count()`` or ``__len__()`` method. For consistent pagination,
  18. ``QuerySet``\s should be ordered, e.g. with an
  19. :meth:`~django.db.models.query.QuerySet.order_by` clause or with a default
  20. :attr:`~django.db.models.Options.ordering` on the model.
  21. .. admonition:: Performance issues paginating large ``QuerySet``\s
  22. If you're using a ``QuerySet`` with a very large number of items,
  23. requesting high page numbers might be slow on some databases, because
  24. the resulting ``LIMIT``/``OFFSET`` query needs to count the number of
  25. ``OFFSET`` records which takes longer as the page number gets higher.
  26. .. attribute:: Paginator.per_page
  27. Required. The maximum number of items to include on a page, not including
  28. orphans (see the :attr:`~Paginator.orphans` optional argument below).
  29. .. attribute:: Paginator.orphans
  30. Optional. Use this when you don't want to have a last page with very few
  31. items. If the last page would normally have a number of items less than or
  32. equal to ``orphans``, then those items will be added to the previous page
  33. (which becomes the last page) instead of leaving the items on a page by
  34. themselves. For example, with 23 items, ``per_page=10``, and ``orphans=3``,
  35. there will be two pages; the first page with 10 items and the second
  36. (and last) page with 13 items. ``orphans`` defaults to zero, which means
  37. pages are never combined and the last page may have one item.
  38. .. attribute:: Paginator.allow_empty_first_page
  39. Optional. Whether or not the first page is allowed to be empty. If
  40. ``False`` and ``object_list`` is empty, then an ``EmptyPage`` error will
  41. be raised.
  42. .. attribute:: Paginator.error_messages
  43. The ``error_messages`` argument lets you override the default messages that
  44. the paginator will raise. Pass in a dictionary with keys matching the error
  45. messages you want to override. Available error message keys are:
  46. ``invalid_page``, ``min_page``, and ``no_results``.
  47. For example, here is the default error message:
  48. .. code-block:: pycon
  49. >>> from django.core.paginator import Paginator
  50. >>> paginator = Paginator([1, 2, 3], 2)
  51. >>> paginator.page(5)
  52. Traceback (most recent call last):
  53. ...
  54. EmptyPage: That page contains no results
  55. And here is a custom error message:
  56. .. code-block:: pycon
  57. >>> paginator = Paginator(
  58. ... [1, 2, 3],
  59. ... 2,
  60. ... error_messages={"no_results": "Page does not exist"},
  61. ... )
  62. >>> paginator.page(5)
  63. Traceback (most recent call last):
  64. ...
  65. EmptyPage: Page does not exist
  66. Methods
  67. -------
  68. .. method:: Paginator.get_page(number)
  69. Returns a :class:`Page` object with the given 1-based index, while also
  70. handling out of range and invalid page numbers.
  71. If the page isn't a number, it returns the first page. If the page number
  72. is negative or greater than the number of pages, it returns the last page.
  73. Raises an :exc:`EmptyPage` exception only if you specify
  74. ``Paginator(..., allow_empty_first_page=False)`` and the ``object_list`` is
  75. empty.
  76. .. method:: Paginator.page(number)
  77. Returns a :class:`Page` object with the given 1-based index. Raises
  78. :exc:`PageNotAnInteger` if the ``number`` cannot be converted to an integer
  79. by calling ``int()``. Raises :exc:`EmptyPage` if the given page number
  80. doesn't exist.
  81. .. method:: Paginator.get_elided_page_range(number, *, on_each_side=3, on_ends=2)
  82. Returns a 1-based list of page numbers similar to
  83. :attr:`Paginator.page_range`, but may add an ellipsis to either or both
  84. sides of the current page number when :attr:`Paginator.num_pages` is large.
  85. The number of pages to include on each side of the current page number is
  86. determined by the ``on_each_side`` argument which defaults to 3.
  87. The number of pages to include at the beginning and end of page range is
  88. determined by the ``on_ends`` argument which defaults to 2.
  89. For example, with the default values for ``on_each_side`` and ``on_ends``,
  90. if the current page is 10 and there are 50 pages, the page range will be
  91. ``[1, 2, '…', 7, 8, 9, 10, 11, 12, 13, '…', 49, 50]``. This will result in
  92. pages 7, 8, and 9 to the left of and 11, 12, and 13 to the right of the
  93. current page as well as pages 1 and 2 at the start and 49 and 50 at the
  94. end.
  95. Raises :exc:`InvalidPage` if the given page number doesn't exist.
  96. Attributes
  97. ----------
  98. .. attribute:: Paginator.ELLIPSIS
  99. A translatable string used as a substitute for elided page numbers in the
  100. page range returned by :meth:`~Paginator.get_elided_page_range`. Default is
  101. ``'…'``.
  102. .. attribute:: Paginator.count
  103. The total number of objects, across all pages.
  104. .. note::
  105. When determining the number of objects contained in ``object_list``,
  106. ``Paginator`` will first try calling ``object_list.count()``. If
  107. ``object_list`` has no ``count()`` method, then ``Paginator`` will
  108. fall back to using ``len(object_list)``. This allows objects, such as
  109. ``QuerySet``, to use a more efficient ``count()`` method when
  110. available.
  111. .. attribute:: Paginator.num_pages
  112. The total number of pages.
  113. .. attribute:: Paginator.page_range
  114. A 1-based range iterator of page numbers, e.g. yielding ``[1, 2, 3, 4]``.
  115. ``AsyncPaginator`` class
  116. ========================
  117. .. versionadded:: 6.0
  118. .. class:: AsyncPaginator(object_list, per_page, orphans=0, allow_empty_first_page=True, error_messages=None)
  119. Asynchronous version of :class:`Paginator`.
  120. ``AsyncPaginator`` has the same attributes and signatures as
  121. :class:`Paginator`, with the following exceptions:
  122. * The attribute :attr:`.Paginator.count` is supported as an asynchronous
  123. method ``AsyncPaginator.acount()``.
  124. * The attribute :attr:`.Paginator.num_pages` is supported as an
  125. asynchronous method ``AsyncPaginator.anum_pages()``.
  126. * The attribute :attr:`.Paginator.page_range` is supported as an
  127. asynchronous method ``AsyncPaginator.apage_range()``.
  128. ``AsyncPaginator`` has asynchronous versions of the same methods as
  129. :class:`Paginator`, using an ``a`` prefix - for example, use
  130. ``await async_paginator.aget_page(number)`` rather than
  131. ``paginator.get_page(number)``.
  132. ``Page`` class
  133. ==============
  134. You usually won't construct ``Page`` objects by hand -- you'll get them by
  135. iterating :class:`Paginator`, or by using :meth:`Paginator.page`.
  136. .. class:: Page(object_list, number, paginator)
  137. A page acts like a sequence of :attr:`Page.object_list` when using
  138. ``len()`` or iterating it directly.
  139. Methods
  140. -------
  141. .. method:: Page.has_next()
  142. Returns ``True`` if there's a next page.
  143. .. method:: Page.has_previous()
  144. Returns ``True`` if there's a previous page.
  145. .. method:: Page.has_other_pages()
  146. Returns ``True`` if there's a next **or** previous page.
  147. .. method:: Page.next_page_number()
  148. Returns the next page number. Raises :exc:`InvalidPage` if next page
  149. doesn't exist.
  150. .. method:: Page.previous_page_number()
  151. Returns the previous page number. Raises :exc:`InvalidPage` if previous
  152. page doesn't exist.
  153. .. method:: Page.start_index()
  154. Returns the 1-based index of the first object on the page, relative to all
  155. of the objects in the paginator's list. For example, when paginating a list
  156. of 5 objects with 2 objects per page, the second page's
  157. :meth:`~Page.start_index` would return ``3``.
  158. .. method:: Page.end_index()
  159. Returns the 1-based index of the last object on the page, relative to all
  160. of the objects in the paginator's list. For example, when paginating a list
  161. of 5 objects with 2 objects per page, the second page's
  162. :meth:`~Page.end_index` would return ``4``.
  163. Attributes
  164. ----------
  165. .. attribute:: Page.object_list
  166. The list of objects on this page.
  167. .. attribute:: Page.number
  168. The 1-based page number for this page.
  169. .. attribute:: Page.paginator
  170. The associated :class:`Paginator` object.
  171. ``AsyncPage`` class
  172. ===================
  173. .. versionadded:: 6.0
  174. .. class:: AsyncPage(object_list, number, paginator)
  175. Asynchronous version of :class:`Page`.
  176. ``AsyncPage`` has the same attributes and signatures as :class:`Page`, as
  177. well as asynchronous versions of all the same methods, using an ``a``
  178. prefix - for example, use ``await async_page.ahas_next()`` rather than
  179. ``page.has_next()``.
  180. ``AsyncPage`` has the following additional method:
  181. .. method:: AsyncPage.aget_object_list()
  182. Returns ``AsyncPage.object_list`` as a list. This method must be
  183. awaited before ``AsyncPage`` can be treated as a sequence of
  184. ``AsyncPage.object_list``.
  185. Exceptions
  186. ==========
  187. .. exception:: InvalidPage
  188. A base class for exceptions raised when a paginator is passed an invalid
  189. page number.
  190. The :meth:`Paginator.page` method raises an exception if the requested page is
  191. invalid (i.e. not an integer) or contains no objects. Generally, it's enough
  192. to catch the ``InvalidPage`` exception, but if you'd like more granularity,
  193. you can catch either of the following exceptions:
  194. .. exception:: PageNotAnInteger
  195. Raised when :meth:`~Paginator.page` is given a value that isn't an integer.
  196. .. exception:: EmptyPage
  197. Raised when :meth:`~Paginator.page` is given a valid value but no objects
  198. exist on that page.
  199. Both of the exceptions are subclasses of :exc:`InvalidPage`, so you can handle
  200. them both with ``except InvalidPage``.