Code

Ticket #11596: 11596.2.diff

File 11596.2.diff, 2.0 KB (added by SmileyChris, 3 years ago)
Line 
1diff --git a/django/core/paginator.py b/django/core/paginator.py
2index 495cdf2..479cb49 100644
3--- a/django/core/paginator.py
4+++ b/django/core/paginator.py
5@@ -1,4 +1,5 @@
6 from math import ceil
7+import collections
8 
9 class InvalidPage(Exception):
10     pass
11@@ -75,7 +76,7 @@ class Paginator(object):
12 
13 QuerySetPaginator = Paginator # For backwards-compatibility.
14 
15-class Page(object):
16+class Page(collections.Sequence):
17     def __init__(self, object_list, number, paginator):
18         self.object_list = object_list
19         self.number = number
20@@ -84,6 +85,14 @@ class Page(object):
21     def __repr__(self):
22         return '<Page %s of %s>' % (self.number, self.paginator.num_pages)
23 
24+    def __len__(self):
25+        return len(self.object_list)
26+
27+    def __getitem__(self, index):
28+        # The object_list is converted to a list so that if it was a QuerySet
29+        # it won't be a database hit per __getitem__.
30+        return list(self.object_list)[index]
31+
32     def has_next(self):
33         return self.number < self.paginator.num_pages
34 
35diff --git a/tests/regressiontests/pagination_regress/tests.py b/tests/regressiontests/pagination_regress/tests.py
36index 28fe316..1cddd43 100644
37--- a/tests/regressiontests/pagination_regress/tests.py
38+++ b/tests/regressiontests/pagination_regress/tests.py
39@@ -154,3 +154,14 @@ class PaginatorTests(TestCase):
40         self.assertRaises(EmptyPage, self.check_indexes, ([], 4, 0, False), 1, None)
41         self.assertRaises(EmptyPage, self.check_indexes, ([], 4, 1, False), 1, None)
42         self.assertRaises(EmptyPage, self.check_indexes, ([], 4, 2, False), 1, None)
43+
44+    def test_page_sequence(self):
45+        """
46+        Tests that a paginator page acts like a standard sequence.
47+        """
48+        eleven = 'abcdefghijk'
49+        page2 = Paginator(eleven, per_page=5, orphans=1).page(2)
50+        self.assertEqual(len(page2), 6)
51+        self.assertTrue('k' in page2)
52+        self.assertFalse('a' in page2)
53+        self.assertEqual(''.join(page2), 'fghijk')