OFFSET不能为负值



当分页对象的结果为0时,我们强制?page=-1那么我们将得到误差OFFSET must not be negative

默认情况下,

-1将获得最后一页。

所以,如果你在url中添加了这个参数,你可能会导致一个内部错误,如果输出是空的分页。

例子:

 page = request.args.get('page', 1, type=int)
 pagination = company.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=current_app.config['COMMENTS_PER_PAGE'],
        error_out=False)

这将避免错误,但是总是使用这种类型的验证来处理潜在的空分页是很烦人的。

 if company.comments.count() > 0:
      pagination = ...    
 else:
      pagination=None

我的问题是关于处理这个特定的内部服务器错误的最佳方法。

这可能是您想要做的,但是sqlalchemy不会为您求值。

我的建议是自己计算页数,然后简单地减去1。

from sqlalchemy import func
if page < 1:
    count = session.query(func.count(Comments.id)).scalar()
    comments_per_page = current_app.config['COMMENTS_PER_PAGE']
    page = count/float(comments_per_page) -1 # gets the last page

请注意,这是未经测试的

最新更新