Fixed #14218 -- Added Paginator.__iter__().

This commit is contained in:
Tanner Stirrat 2019-09-20 15:04:34 -06:00 committed by Carlton Gibson
parent 84322a29ce
commit 17595407ca
4 changed files with 25 additions and 2 deletions

View File

@ -34,6 +34,10 @@ class Paginator:
self.orphans = int(orphans) self.orphans = int(orphans)
self.allow_empty_first_page = allow_empty_first_page self.allow_empty_first_page = allow_empty_first_page
def __iter__(self):
for page_number in self.page_range:
yield self.page(page_number)
def validate_number(self, number): def validate_number(self, number):
"""Validate the given 1-based page number.""" """Validate the given 1-based page number."""
try: try:

View File

@ -14,6 +14,13 @@ classes live in :source:`django/core/paginator.py`.
.. class:: Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True) .. class:: Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)
A paginator acts like a sequence of :class:`Page` when using ``len()`` or
iterating it directly.
.. versionchanged:: 3.1
Support for iterating over ``Paginator`` was added.
.. attribute:: Paginator.object_list .. attribute:: Paginator.object_list
Required. A list, tuple, ``QuerySet``, or other sliceable object with a Required. A list, tuple, ``QuerySet``, or other sliceable object with a
@ -98,8 +105,8 @@ Attributes
``Page`` class ``Page`` class
============== ==============
You usually won't construct ``Page`` objects by hand -- you'll get them using You usually won't construct ``Page`` objects by hand -- you'll get them by
:meth:`Paginator.page`. iterating :class:`Paginator`, or by using :meth:`Paginator.page`.
.. class:: Page(object_list, number, paginator) .. class:: Page(object_list, number, paginator)

View File

@ -162,6 +162,11 @@ Models
* ... * ...
Pagination
~~~~~~~~~~
* Support for iterating over ``Paginator`` was added.
Requests and Responses Requests and Responses
~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~

View File

@ -297,6 +297,13 @@ class PaginationTests(SimpleTestCase):
with self.assertRaises(EmptyPage): with self.assertRaises(EmptyPage):
paginator.get_page(1) paginator.get_page(1)
def test_paginator_iteration(self):
paginator = Paginator([1, 2, 3], 2)
page_iterator = iter(paginator)
for page, expected in enumerate(([1, 2], [3]), start=1):
with self.subTest(page=page):
self.assertEqual(expected, list(next(page_iterator)))
class ModelPaginationTests(TestCase): class ModelPaginationTests(TestCase):
""" """