python反向分页

时间:2013-01-27 00:10:49

标签: google-app-engine app-engine-ndb

我试图根据google appengine文档

的示例进行反向分页

NDB Query Cursor

我的问题集中在这个例子上:

# 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)

基于这个例子,我创建了自己的版本(像这样):

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()+"\">&laquo</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()+"\">&raquo</a>")

但我仍然不明白为什么,它无法完美地回到上一页...... 当我点击第1页到第2页时:

第1页:a,b 第2页:c,d

但是当我向后点击时:

第2页:c,d 第1页:b,c(应该是:a,b)

它使我很困惑,因为论坛上的某个人可以根据这个例子让它工作,并且没有人从他们那里提供示例代码......

1 个答案:

答案 0 :(得分:2)

问题是您使用c来引用前后光标。

因此,当你得到一个已被反转的向后光标时,你正在调用

rev_cursor = cursor.reversed()

bars1, prev_cursor, more1 = q_reverse.fetch_page(2, start_cursor=rev_cursor)

所以光标在开始查询之前开始指向另一个方向。

要查看更简单的测试,请定义相同的模型并预先填充一些数据:

from google.appengine.ext import ndb
class Testing(ndb.Model):
  t = ndb.StringProperty()
ndb.put_multi([Testing(t='a'), Testing(t='b'), Testing(t='c')])

通过查询前两个元素来获取游标:

>>> q_forward = Testing.query().order(Testing.t)
>>> result, forward_cursor, _ = q_forward.fetch_page(2)
>>> print [value.t for value in result]
[u'a', u'b']

反向查询中使用该光标而不将其反转

>>> reverse_cursor = forward_cursor.reversed()
>>> result, _, _ = q_reverse.fetch_page(2, start_cursor=reverse_cursor)
>>> print [value.t for value in result]
[u'b', u'a']
执行此操作后,

与反向查询相比: