pagination.txt 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. >>> p.page_range
  22. [1, 2]
  23. >>> page1 = p.page(1)
  24. >>> page1
  25. <Page 1 of 2>
  26. >>> page1.object_list
  27. ['john', 'paul']
  28. >>> page2 = p.page(2)
  29. >>> page2.object_list
  30. ['george', 'ringo']
  31. >>> page2.has_next()
  32. False
  33. >>> page2.has_previous()
  34. True
  35. >>> page2.has_other_pages()
  36. True
  37. >>> page2.next_page_number()
  38. Traceback (most recent call last):
  39. ...
  40. EmptyPage: That page contains no results
  41. >>> page2.previous_page_number()
  42. 1
  43. >>> page2.start_index() # The 1-based index of the first item on this page
  44. 3
  45. >>> page2.end_index() # The 1-based index of the last item on this page
  46. 4
  47. >>> p.page(0)
  48. Traceback (most recent call last):
  49. ...
  50. EmptyPage: That page number is less than 1
  51. >>> p.page(3)
  52. Traceback (most recent call last):
  53. ...
  54. EmptyPage: That page contains no results
  55. .. note::
  56. Note that you can give ``Paginator`` a list/tuple, a Django ``QuerySet``,
  57. or any other object with a ``count()`` or ``__len__()`` method. When
  58. determining the number of objects contained in the passed object,
  59. ``Paginator`` will first try calling ``count()``, then fallback to using
  60. ``len()`` if the passed object has no ``count()`` method. This allows
  61. objects such as Django's ``QuerySet`` to use a more efficient ``count()``
  62. method when available.
  63. Using ``Paginator`` in a view
  64. ==============================
  65. Here's a slightly more complex example using :class:`Paginator` in a view to
  66. paginate a queryset. We give both the view and the accompanying template to
  67. show how you can display the results. This example assumes you have a
  68. ``Contacts`` model that has already been imported.
  69. The view function looks like this::
  70. from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
  71. def listing(request):
  72. contact_list = Contacts.objects.all()
  73. paginator = Paginator(contact_list, 25) # Show 25 contacts per page
  74. page = request.GET.get('page')
  75. try:
  76. contacts = paginator.page(page)
  77. except PageNotAnInteger:
  78. # If page is not an integer, deliver first page.
  79. contacts = paginator.page(1)
  80. except EmptyPage:
  81. # If page is out of range (e.g. 9999), deliver last page of results.
  82. contacts = paginator.page(paginator.num_pages)
  83. return render_to_response('list.html', {"contacts": contacts})
  84. In the template :file:`list.html`, you'll want to include navigation between
  85. pages along with any interesting information from the objects themselves::
  86. {% for contact in contacts %}
  87. {# Each "contact" is a Contact model object. #}
  88. {{ contact.full_name|upper }}<br />
  89. ...
  90. {% endfor %}
  91. <div class="pagination">
  92. <span class="step-links">
  93. {% if contacts.has_previous %}
  94. <a href="?page={{ contacts.previous_page_number }}">previous</a>
  95. {% endif %}
  96. <span class="current">
  97. Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}.
  98. </span>
  99. {% if contacts.has_next %}
  100. <a href="?page={{ contacts.next_page_number }}">next</a>
  101. {% endif %}
  102. </span>
  103. </div>
  104. ``Paginator`` objects
  105. =====================
  106. The :class:`Paginator` class has this constructor:
  107. .. class:: Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)
  108. Required arguments
  109. ------------------
  110. ``object_list``
  111. A list, tuple, Django ``QuerySet``, or other sliceable object with a
  112. ``count()`` or ``__len__()`` method.
  113. ``per_page``
  114. The maximum number of items to include on a page, not including orphans
  115. (see the ``orphans`` optional argument below).
  116. Optional arguments
  117. ------------------
  118. ``orphans``
  119. The minimum number of items allowed on the last page, defaults to zero.
  120. Use this when you don't want to have a last page with very few items.
  121. If the last page would normally have a number of items less than or equal
  122. to ``orphans``, then those items will be added to the previous page (which
  123. becomes the last page) instead of leaving the items on a page by
  124. themselves. For example, with 23 items, ``per_page=10``, and
  125. ``orphans=3``, there will be two pages; the first page with 10 items and
  126. the second (and last) page with 13 items.
  127. ``allow_empty_first_page``
  128. Whether or not the first page is allowed to be empty. If ``False`` and
  129. ``object_list`` is empty, then an ``EmptyPage`` error will be raised.
  130. Methods
  131. -------
  132. .. method:: Paginator.page(number)
  133. Returns a :class:`Page` object with the given 1-based index. Raises
  134. :exc:`InvalidPage` if the given page number doesn't exist.
  135. Attributes
  136. ----------
  137. .. attribute:: Paginator.count
  138. The total number of objects, across all pages.
  139. .. note::
  140. When determining the number of objects contained in ``object_list``,
  141. ``Paginator`` will first try calling ``object_list.count()``. If
  142. ``object_list`` has no ``count()`` method, then ``Paginator`` will
  143. fallback to using ``len(object_list)``. This allows objects, such as
  144. Django's ``QuerySet``, to use a more efficient ``count()`` method when
  145. available.
  146. .. attribute:: Paginator.num_pages
  147. The total number of pages.
  148. .. attribute:: Paginator.page_range
  149. A 1-based range of page numbers, e.g., ``[1, 2, 3, 4]``.
  150. ``InvalidPage`` exceptions
  151. ==========================
  152. .. exception:: InvalidPage
  153. A base class for exceptions raised when a paginator is passed an invalid
  154. page number.
  155. The :meth:`Paginator.page` method raises an exception if the requested page is
  156. invalid (i.e., not an integer) or contains no objects. Generally, it's enough
  157. to catch the ``InvalidPage`` exception, but if you'd like more granularity,
  158. you can catch either of the following exceptions:
  159. .. exception:: PageNotAnInteger
  160. Raised when ``page()`` is given a value that isn't an integer.
  161. .. exception:: EmptyPage
  162. Raised when ``page()`` is given a valid value but no objects exist on that
  163. page.
  164. Both of the exceptions are subclasses of :exc:`InvalidPage`, so you can handle
  165. them both with a simple ``except InvalidPage``.
  166. ``Page`` objects
  167. ================
  168. You usually won't construct ``Page`` objects by hand -- you'll get them
  169. using :meth:`Paginator.page`.
  170. .. class:: Page(object_list, number, paginator)
  171. A page acts like a sequence of :attr:`Page.object_list` when using
  172. ``len()`` or iterating it directly.
  173. Methods
  174. -------
  175. .. method:: Page.has_next()
  176. Returns ``True`` if there's a next page.
  177. .. method:: Page.has_previous()
  178. Returns ``True`` if there's a previous page.
  179. .. method:: Page.has_other_pages()
  180. Returns ``True`` if there's a next *or* previous page.
  181. .. method:: Page.next_page_number()
  182. Returns the next page number. Raises :exc:`InvalidPage` if next page
  183. doesn't exist.
  184. .. method:: Page.previous_page_number()
  185. Returns the previous page number. Raises :exc:`InvalidPage` if previous
  186. page doesn't exist.
  187. .. method:: Page.start_index()
  188. Returns the 1-based index of the first object on the page, relative to all
  189. of the objects in the paginator's list. For example, when paginating a list
  190. of 5 objects with 2 objects per page, the second page's
  191. :meth:`~Page.start_index` would return ``3``.
  192. .. method:: Page.end_index()
  193. Returns the 1-based index of the last object on the page, relative to all
  194. of the objects in the paginator's list. For example, when paginating a list
  195. of 5 objects with 2 objects per page, the second page's
  196. :meth:`~Page.end_index` would return ``4``.
  197. Attributes
  198. ----------
  199. .. attribute:: Page.object_list
  200. The list of objects on this page.
  201. .. attribute:: Page.number
  202. The 1-based page number for this page.
  203. .. attribute:: Page.paginator
  204. The associated :class:`Paginator` object.