1eec6f53b2
Fixes #1591
29 lines
960 B
Python
29 lines
960 B
Python
def paginate(query, model, descending=False, page_token=None, limit=50, id_field='id'):
|
|
""" Paginates the given query using an ID range, starting at the optional page_token.
|
|
Returns a *list* of matching results along with an unencrypted page_token for the
|
|
next page, if any. If descending is set to True, orders by the ID descending rather
|
|
than ascending.
|
|
"""
|
|
query = query.limit(limit + 1)
|
|
|
|
if descending:
|
|
query = query.order_by(getattr(model, id_field).desc())
|
|
else:
|
|
query = query.order_by(getattr(model, id_field))
|
|
|
|
if page_token is not None:
|
|
start_id = page_token.get('start_id')
|
|
if start_id is not None:
|
|
if descending:
|
|
query = query.where(model.id <= start_id)
|
|
else:
|
|
query = query.where(model.id >= start_id)
|
|
|
|
results = list(query)
|
|
page_token = None
|
|
if len(results) > limit:
|
|
page_token = {
|
|
'start_id': results[limit].id
|
|
}
|
|
|
|
return results[0:limit], page_token
|