Fix the Repository ID in pagination problem once and for all
But.... ONCE AND FOR ALL! Note: Tested on SQLite, Postgres and MySQL
This commit is contained in:
parent
1ed1bc9ed3
commit
4e1259b58a
2 changed files with 16 additions and 10 deletions
|
@ -1,29 +1,34 @@
|
|||
def paginate(query, model, descending=False, page_token=None, limit=50, id_field='id'):
|
||||
from peewee import SQL
|
||||
|
||||
def paginate(query, model, descending=False, page_token=None, limit=50, id_alias=None):
|
||||
""" 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)
|
||||
id_field = model.id
|
||||
if id_alias is not None:
|
||||
id_field = SQL(id_alias)
|
||||
|
||||
if descending:
|
||||
query = query.order_by(getattr(model, id_field).desc())
|
||||
query = query.order_by(id_field.desc())
|
||||
else:
|
||||
query = query.order_by(getattr(model, id_field))
|
||||
query = query.order_by(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(getattr(model, id_field) <= start_id)
|
||||
query = query.where(model.id <= start_id)
|
||||
else:
|
||||
query = query.where(getattr(model, id_field) >= start_id)
|
||||
query = query.where(model.id >= start_id)
|
||||
|
||||
results = list(query)
|
||||
page_token = None
|
||||
if len(results) > limit:
|
||||
start_id = results[limit].id
|
||||
page_token = {
|
||||
'start_id': getattr(results[limit], id_field)
|
||||
'start_id': start_id
|
||||
}
|
||||
|
||||
return results[0:limit], page_token
|
||||
|
|
Reference in a new issue