Skip to content

Commit

Permalink
cursor pagination betterified added
Browse files Browse the repository at this point in the history
  • Loading branch information
Bishwas-py committed Mar 9, 2024
1 parent 4cf6797 commit 14f144e
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 10 deletions.
Binary file modified djapy/core/__pycache__/dec.cpython-311.pyc
Binary file not shown.
1 change: 1 addition & 0 deletions djapy/core/dec.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ def _wrapped_view(request: HttpRequest, *args, **view_kwargs):
name: (type_name_, default)
for name, type_name_, default in pagination_class.query
}
print(extra_query_dict)

_wrapped_view.djapy = True
_wrapped_view.openapi = openapi
Expand Down
20 changes: 10 additions & 10 deletions djapy/core/pagination/cursor_pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ class CursorPagination(BasePagination):
"""Cursor-based pagination."""

query = [
('cursor', str, '0'),
('limit', conint(gt=0), 10)
('cursor', conint(ge=0), 0),
('limit', conint(ge=0), 1)
]

class response(Schema, Generic[G_TYPE]):
items: G_TYPE
cursor: str
cursor: int | None
limit: int
has_next: bool

Expand All @@ -31,15 +31,15 @@ def make_data(cls, queryset, info):
cursor = info.context['input_data']['cursor']
limit = info.context['input_data']['limit']

queryset = queryset.order_by('id') # order by some field in a unique, sequential manner
# Convert the cursor to integer and get the subset
cursor = int(cursor)
queryset_subset = queryset.filter(id__gt=cursor)[:limit]
queryset = queryset.order_by('id')

has_next = len(queryset.filter(id__gt=cursor)) > limit
queryset_with_cursor = queryset.filter(id__gt=cursor)

# After processing the queryset, the cursor will be set to the id of the last item
cursor = str(queryset_subset.last().id) if has_next else None
has_next = queryset_with_cursor.count() > limit

queryset_subset = list(queryset_with_cursor[:limit])

cursor = queryset_subset[-1].id if queryset_subset and has_next else None

return {
"items": queryset_subset,
Expand Down

0 comments on commit 14f144e

Please sign in to comment.