Search code examples
google-app-enginedjango-nonreldjangoappengine

How to reverse a cursor in djangoappengine?


I'm developing and application that requires to paginate a list of links. I'm using django non-rel with djangoappengine.

I'm aware of the functions set_cursor and get_cursor found in djangoappengine.db.utils which make it easy to navigate forward as such:

paginate_by = 25
queryset = Link.objects.all()

cursor = request.GET.get('cursor') #Alternatively passed via ajax in a POST request
if cursor:
    queryset = set_cursor(queryset, cursor)

links = queryset[0:paginate_by]
next_cursor = get_cursor(links)

However, I'm struggling to navigate backwards. The official procedure in GAE is to reverse the cursor and to use a reversed query. This makes use of a reversed() function that is part of the Cursor class, which I'm unsure I can access in Django.

But how do I reverse a cursor in djangoappengie?

In case it is not possible I believe that the alternative is to store the cursors client side, pass them via ajax, and then generate a query based on page number. I would prefer to follow the official procedures as much as possible, though.

Thanks


Solution

  • I don't know what the policy on answering your own question is... After further research I found a function that reverses a cursor, namely:

    from google.appengine.datastore import datastore_query
    def reverse_cursor(cursor):
        return datastore_query.Cursor.from_websafe_string(cursor).reversed().to_websafe_string()
    

    I'll store this in my utils.py and getting a reversed cursor should be simple.