Fix pagination when asking for the last page on a query that matches no records

This commit is contained in:
Itai Shirav 2019-02-26 22:58:59 +02:00
parent bec45b53fa
commit 81e942a4d2
3 changed files with 11 additions and 2 deletions

View File

@ -5,6 +5,7 @@ Unreleased
---------- ----------
- Extend date field range (trthhrtz) - Extend date field range (trthhrtz)
- Fix parsing of server errors in ClickHouse v19.3.3+ - Fix parsing of server errors in ClickHouse v19.3.3+
- Fix pagination when asking for the last page on a query that matches no records
v1.0.4 v1.0.4
------ ------

View File

@ -285,7 +285,7 @@ class Database(object):
count = self.count(model_class, conditions) count = self.count(model_class, conditions)
pages_total = int(ceil(count / float(page_size))) pages_total = int(ceil(count / float(page_size)))
if page_num == -1: if page_num == -1:
page_num = pages_total page_num = max(pages_total, 1)
elif page_num < 1: elif page_num < 1:
raise ValueError('Invalid page number: %d' % page_num) raise ValueError('Invalid page number: %d' % page_num)
offset = (page_num - 1) * page_size offset = (page_num - 1) * page_size
@ -296,7 +296,7 @@ class Database(object):
query += ' LIMIT %d, %d' % (offset, page_size) query += ' LIMIT %d, %d' % (offset, page_size)
query = self._substitute(query, model_class) query = self._substitute(query, model_class)
return Page( return Page(
objects=list(self.select(query, model_class, settings)), objects=list(self.select(query, model_class, settings)) if count else [],
number_of_objects=count, number_of_objects=count,
pages_total=pages_total, pages_total=pages_total,
number=page_num, number=page_num,

View File

@ -112,6 +112,14 @@ class DatabaseTestCase(TestCaseWithData):
self.assertEqual([obj.to_tsv() for obj in page_a.objects], self.assertEqual([obj.to_tsv() for obj in page_a.objects],
[obj.to_tsv() for obj in page_b.objects]) [obj.to_tsv() for obj in page_b.objects])
def test_pagination_empty_page(self):
for page_num in (-1, 1, 2):
page = self.database.paginate(Person, 'first_name, last_name', page_num, 10, conditions="first_name = 'Ziggy'")
self.assertEqual(page.number_of_objects, 0)
self.assertEqual(page.objects, [])
self.assertEqual(page.pages_total, 0)
self.assertEqual(page.number, max(page_num, 1))
def test_pagination_invalid_page(self): def test_pagination_invalid_page(self):
self._insert_and_check(self._sample_data(), len(data)) self._insert_and_check(self._sample_data(), len(data))
for page_num in (0, -2, -100): for page_num in (0, -2, -100):