pagination.txt 8.4 KB

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