mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-03-29 06:14:25 +03:00
Prevent raising exception when limit is 0 (#4098)
This commit is contained in:
parent
5ac9685139
commit
0795f7394c
|
@ -36,10 +36,11 @@ def _positive_int(integer_string, strict=False, cutoff=None):
|
|||
|
||||
def _divide_with_ceil(a, b):
|
||||
"""
|
||||
Returns 'a' divded by 'b', with any remainder rounded up.
|
||||
Returns 'a' divided by 'b', with any remainder rounded up.
|
||||
"""
|
||||
if a % b:
|
||||
return (a // b) + 1
|
||||
|
||||
return a // b
|
||||
|
||||
|
||||
|
@ -358,17 +359,24 @@ class LimitOffsetPagination(BasePagination):
|
|||
|
||||
def get_html_context(self):
|
||||
base_url = self.request.build_absolute_uri()
|
||||
current = _divide_with_ceil(self.offset, self.limit) + 1
|
||||
# The number of pages is a little bit fiddly.
|
||||
# We need to sum both the number of pages from current offset to end
|
||||
# plus the number of pages up to the current offset.
|
||||
# When offset is not strictly divisible by the limit then we may
|
||||
# end up introducing an extra page as an artifact.
|
||||
final = (
|
||||
_divide_with_ceil(self.count - self.offset, self.limit) +
|
||||
_divide_with_ceil(self.offset, self.limit)
|
||||
)
|
||||
if final < 1:
|
||||
|
||||
if self.limit:
|
||||
current = _divide_with_ceil(self.offset, self.limit) + 1
|
||||
|
||||
# The number of pages is a little bit fiddly.
|
||||
# We need to sum both the number of pages from current offset to end
|
||||
# plus the number of pages up to the current offset.
|
||||
# When offset is not strictly divisible by the limit then we may
|
||||
# end up introducing an extra page as an artifact.
|
||||
final = (
|
||||
_divide_with_ceil(self.count - self.offset, self.limit) +
|
||||
_divide_with_ceil(self.offset, self.limit)
|
||||
)
|
||||
|
||||
if final < 1:
|
||||
final = 1
|
||||
else:
|
||||
current = 1
|
||||
final = 1
|
||||
|
||||
if current > final:
|
||||
|
|
|
@ -505,6 +505,31 @@ class TestLimitOffset:
|
|||
assert content.get('next') == next_url
|
||||
assert content.get('previous') == prev_url
|
||||
|
||||
def test_limit_zero(self):
|
||||
"""
|
||||
A limit of 0 should return empty results.
|
||||
"""
|
||||
request = Request(factory.get('/', {'limit': 0, 'offset': 10}))
|
||||
queryset = self.paginate_queryset(request)
|
||||
context = self.get_html_context()
|
||||
content = self.get_paginated_content(queryset)
|
||||
|
||||
assert context == {
|
||||
'previous_url': 'http://testserver/?limit=0&offset=10',
|
||||
'page_links': [
|
||||
PageLink(
|
||||
url='http://testserver/?limit=0',
|
||||
number=1,
|
||||
is_active=True,
|
||||
is_break=False
|
||||
)
|
||||
],
|
||||
'next_url': 'http://testserver/?limit=0&offset=10'
|
||||
}
|
||||
|
||||
assert queryset == []
|
||||
assert content.get('results') == []
|
||||
|
||||
|
||||
class TestCursorPagination:
|
||||
"""
|
||||
|
|
Loading…
Reference in New Issue
Block a user