【问题标题】:Find page for a specific item in paginate() SQLAlchemy在 paginate() SQLAlchemy 中查找特定项目的页面
【发布时间】:2015-07-17 07:00:21
【问题描述】:
我使用的是 Flask-SQLAlchemy 的 paginate()。现在我需要找到特定评论 ID 的页面。
例如,如果我将所有 cmets 都放在同一页面中,这将起作用:
new_dict['url'] = '/comments#comment_' + str(comment.id)
但就我而言,我需要这种结构:
/comments?page=1#comment_73
我怎样才能找到页面是什么?
【问题讨论】:
标签:
python
flask
pagination
sqlalchemy
flask-sqlalchemy
【解决方案1】:
从the docs 开始,Pagination 类具有.items 和.has_next 属性以及我们可以使用的.next 方法:
page_number = 0
search = Comment.query.get(15)
query = Comment.query.filter(Comment.id<40)
for num in range(1, query.paginate(1).pages + 1):
if search in query.paginate(num).items:
page_number = num
break
或
page_number = 0
search = Comment.query.get(15)
pag = Comment.query.filter(Comment.id<40).paginate(1)
while pag.has_next:
if search in pag.items:
page_number = num
break
pag.next()
【解决方案2】:
据我所知,Celeo 的回答是行不通的。例如,pag.next() 在他的代码中所做的,根据文档是:
为下一页返回一个分页对象。
所以,基本上,除非你更新你的变量,否则它什么都不做;我建议您不要创建新查询,因为您已经有了 comment_id,所以:
comment_id=request.args.get('comment_id')
if comment_id and comment_id.isdigit():
comment_id = int(comment_id )
page_number = -1
index = 1 # page numbers are 1 indexed in Pagination Object
while comments_pagination_object.has_next:
for comment in comments_pagination_object.items:
if comment.id == comment_id :
page_number = index
break
if page_number != -1:
break
index += 1
product_items = product_items.next()
然后,在 URL 中,您将有如下内容:
/comments?comment_id=2
product_items.next() 部分正在更改 PaginationObject 的页面,直到其中一个项目(在本例中为 class Comment 类型)与您的请求参数具有相同的 id。