【问题标题】:How can I implement pagination with python on google appengine?如何在 google appengine 上使用 python 实现分页?
【发布时间】:2013-04-05 18:29:26
【问题描述】:

我正在建立一个类似 reddit 的网站。对象按等级排序。我希望有人可以帮助我实现分页。我只想先加载前 20 个对象。然后单击“下一步”按钮,我希望根据第 20 个对象的评级加载接下来的 20 个对象。以下是谷歌文档:https://developers.google.com/appengine/docs/python/datastore/queries?hl=en

有人知道这样做的方法吗?或者那里有很好的教程?

【问题讨论】:

    标签: python google-app-engine pagination


    【解决方案1】:

    这是我用来检索我的模型实例和光标的通用函数。该函数接受参数,我从请求中读取它们。

    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
    

    你可以这样称呼它。我使用扩展 entity_db 和 entity_dbs 来表示我的变量引用实体对象,*_db 和 *_dbs 定义是否有一个或多个结果。

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

    【讨论】:

      【解决方案2】:

      如果您在数据存储查询中使用 limit=20,这非常简单,然后获取一个游标以获取下一个 20。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多