应用引擎数据存储分页-上一页



我正在尝试创建分页机制来通过查询进行分页。前进不是问题。然而,跳转到前一页似乎不是微不足道的。

到目前为止我得到的是(为什么我觉得它应该更简单?):

cursor_urlsafe = self.request.get('cursor', None)
rev = bool(self.request.get('rev', None))
cursor = ndb.Cursor(urlsafe=cursor_urlsafe)
if rev:
    next_query = Shot.query(Shot.schedule_key == schedule.key).order(Shot.date_created)
    cursor = cursor.reversed()
else:
    next_query = Shot.query(Shot.schedule_key == schedule.key).order(-Shot.date_created)
shots, next_cursor, more = next_query.fetch_page(PAGE_LENGTH, start_cursor=cursor)
if rev:
    shots.sort(key=lambda x: -x.date_created_epoch)
next_cursor_url_safe = next_cursor.urlsafe() if next_cursor else None
template_params = {
    'shots': shots,
    'next_cursor': next_cursor_url_safe,
    'prev_cursor': next_cursor_url_safe if cursor_urlsafe else None
}

和在客户端:

<a href="/schedule/{{ s.id }}?cursor={{ prev_cursor }}&rev=true">Previous</a><br>
<a href="/schedule/{{ s.id }}?cursor={{ next_cursor }}">Next</a>

这种方法有效。唯一的问题是,当用户"改变方向"(返回页面)时,它会把他带回到他所在的页面,只有在再次点击前一个页面后,它才会回到前一个页面。

如果点击,上一步,下一步我就一直在同一个页面上了

请建议。

您可以采用一些策略。存储以前的游标-请参阅https://p.ota.to/blog/2013/4/pagination-with-cursors-in-the-app-engine-datastore/或搜索SO以获取另一种方法。在给定NDB游标的情况下,获取前页结果的正确方法是什么?

一种解决方案是让客户机在光标向前移动时保留一个光标列表。当它们向后翻页时,使用列表中的上一个光标。后端游标可以导出为字符串。在Java中,使用toUrlSafe方法。在Python中可能有一个等价的。

在使用前一个游标时,我建议删除列表中的最后一个游标,以便在用户页面再次转发时创建它的新实例。不过,这又取决于数据变化的频率。如果数据很少更改,则可以跳过从列表中删除游标,而只使用缓存的游标来加快后端速度。

最新更新