-
Notifications
You must be signed in to change notification settings - Fork 28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add pagination helpers #5
Comments
👍 adding stock pagination helpers would be a huge help |
I ended up doing something like: class PublicListEndpoint(ListEndpoint):
methods = ['GET']
per_page = 100
serialize_config = {}
def filter(self, data, **kwargs):
return data.filter(**kwargs)
def sort(self, data, sort_by):
return data.order_by(*sort_by)
def paginate(self, data, page):
paginator = Paginator(data, per_page=self.per_page)
return paginator.page(page)
def get(self, request, *args, **kwargs):
params = request.params
page = 1
if 'page' in params:
page = int(params.pop('page'))
sort_by = []
if 'sort_by' in params:
sort_by = params.pop('sort_by').split(",")
data = self.get_query_set(request, *args, **kwargs)
data = self.filter(data, **params)
data = self.sort(data, sort_by)
try:
data_page = self.paginate(data, page)
except EmptyPage:
raise HttpError(
404,
'No such page (heh, literally - its out of bounds)'
)
return {
"meta": {
"count": len(data_page.object_list),
"page": page,
"per_page": self.per_page,
"max_page": data_page.end_index(),
"total_count": data.count(),
},
"results": [
serialize(x, **self.serialize_config)
for x in data_page.object_list
]
} for an API endpoint I'm hacking on. (just to get a feel for how others are using restless for this) |
I usually do pagination with I'm thinking of introducing a
Then you could just switch forms (or implement your own) to implement the pagination style you need. Analogous for filtering and sorting. The idea is to add something that wouldn't force you to use a specific way of doing pagination, but would still have the building blocks for the most common forms. |
Django's built-in paginator works in terms of fixed-size pages. While usable in API context, this might pose problems if results are likely to change between subsequent page requests (eg. more data pours in).
A simple pagination model with
since
(all objects after the selected one) andlimit
works better in this case. Here's a sample implementation:Note that this example includes the "since" object in results (in effect, returning it twice).
The text was updated successfully, but these errors were encountered: