This is a generic function that I am using in order to retrieve my model instances along with the cursor. The function takes parameters, which I am reading them from the request.
def retrieve_dbs(query, order=None, limit=None, cursor=None, **filters):
''' Retrieves entities from datastore, by applying cursor pagination
and equality filters. Returns dbs and more cursor value
'''
limit = limit or config.DEFAULT_DB_LIMIT
cursor = Cursor.from_websafe_string(cursor) if cursor else None
model_class = ndb.Model._kind_map[query.kind]
if order:
for o in order.split(','):
if o.startswith('-'):
query = query.order(-model_class._properties[o[1:]])
else:
query = query.order(model_class._properties[o])
for prop in filters:
if filters.get(prop, None) is None:
continue
if type(filters[prop]) == list:
for value in filters[prop]:
query = query.filter(model_class._properties[prop] == value)
else:
query = query.filter(model_class._properties[prop] == filters[prop])
model_dbs, more_cursor, more = query.fetch_page(limit, start_cursor=cursor)
more_cursor = more_cursor.to_websafe_string() if more else None
return list(model_dbs), more_cursor
You can call it in that fashion. I am using the extentions entity_db and entity_dbs to signify that my variables refer to an entity object, *_db and *_dbs define if there are one or many results.
entity_dbs, entity_cursor = retrieve_dbs(
model.Entity.query(),
limit=limit, # Your limit parameter
cursor=cursor, # The cursor if you want to grab a batch of next results
order=order,
)