i have tried to make a backward paging, based on the example of google appengine documentation
my question is focused on this example:
# Set up.
q = Bar.query()
q_forward = q.order(Bar.key)
q_reverse = q.order(-Bar.key)
# Fetch a page going forward.
bars, cursor, more = q_forward.fetch_page(10)
# Fetch the same page going backward.
rev_cursor = cursor.reversed()
bars1, cursor1, more1 = q_reverse.fetch_page(10, start_cursor=rev_cursor)
based on this example i create my own version (like this):
def get(self):
#testing = Testing(t="a");
#testing.put();
#testing2 = Testing(t="b");
#testing2.put();
#testing3 = Testing(t="c");
#testing3.put();
#testing4 = Testing(t="d");
#testing4.put();
#testing5 = Testing(t="e");
#testing5.put();
cursor = ndb.Cursor.from_websafe_string(self.request.get("c"))
if cursor:
q = Testing.query()
q_forward = q.order(Testing.key)
q_reverse = q.order(-Testing.key)
bars, next_cursor, more = q_forward.fetch_page(2, start_cursor=cursor)
rev_cursor = cursor.reversed()
bars1, prev_cursor, more1 = q_reverse.fetch_page(2, start_cursor=rev_cursor)
self.response.write("<a href=\"?c="+prev_cursor.to_websafe_string()+"\">«</a><br />")
else:
q = Testing.query()
q_forward = q.order(Testing.key)
q_reverse = q.order(-Testing.key)
bars, next_cursor, more = q_forward.fetch_page(2)
self.response.write('Hello world!<br />')
for bar in bars:
self.response.write(bar.t + "<br />")
self.response.write("<a href=\"?c="+next_cursor.to_websafe_string()+"\">»</a>")
but i still not understand why, it cannot back to previous page perfectly... when i click forward page 1 to page 2:
Page 1 : a, b Page 2 : c, d
but when i click backward:
Page 2: c, d Page 1: b, c (should be: a, b)
it confused me a lot, since somebody at forum, can make it work based on this example, and nobody give an example code from them...
The issue is that you are using
c
to refer to a backwards and forwards cursor.So, when you get a backwards cursor which has already been reversed, you are calling
before
and so the cursor begins pointing in the other direction before beginning the query.
To see a simpler test of this, define the same model and pre-populate some data:
get a cursor by querying for the first two elements:
use that cursor in a reverse query without reversing it
versus in a reverse query after doing so: