Skip to content

Commit ef227ef

Browse files
authored
Fix issue with zero size (#959)
1 parent f25b6de commit ef227ef

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

fastapi_pagination/default.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,13 @@ def create(
6262

6363
size = params.size if params.size is not None else total
6464
page = params.page if params.page is not None else 1
65-
pages = ceil(total / size) if total is not None else None
65+
66+
if size == 0:
67+
pages = 0
68+
elif total is not None:
69+
pages = ceil(total / size)
70+
else:
71+
pages = None
6672

6773
return create_pydantic_model(
6874
cls,

fastapi_pagination/links/default.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def __root_validator__(cls, value: Any) -> Any:
2424

2525
value["links"] = create_links(
2626
first={"page": 1},
27-
last={"page": ceil(total / size) if total > 0 else 1},
27+
last={"page": ceil(total / size) if total > 0 and size > 0 else 1},
2828
next={"page": page + 1} if page * size < total else None,
2929
prev={"page": page - 1} if page - 1 >= 1 else None,
3030
)

tests/test_bases.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import re
22
from typing import ClassVar, Generic, Optional, Sequence, TypeVar
33

4+
from fastapi import Query
45
from pytest import mark, raises, warns
56

67
from fastapi_pagination import Page, Params
@@ -82,6 +83,30 @@ def test_with_custom_options_items_casted():
8283
}
8384

8485

86+
def test_zero_size():
87+
class CustomParams(Params):
88+
size: Optional[int] = Query(0)
89+
90+
class CustomPage(Page[T], Generic[T]):
91+
size: Optional[int] = None
92+
93+
__params_type__ = CustomParams
94+
95+
res = CustomPage[int].create(
96+
[],
97+
CustomParams(),
98+
total=0,
99+
)
100+
101+
assert res.dict() == {
102+
"items": [],
103+
"page": 1,
104+
"pages": 0,
105+
"size": 0,
106+
"total": 0,
107+
}
108+
109+
85110
def test_invalid_params_cast():
86111
with raises(ValueError, match="^Not a 'limit-offset' params$"):
87112
CursorParams().to_raw_params().as_limit_offset()

0 commit comments

Comments
 (0)