pagination.txt 8.2 KB

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