Python Flask分页配方



我正在学习Flask Web开发书,在第13章中,它是关于"博客文章的评论"

post的路由函数如下,书上说"when page = -1",它会计算总共有多少评论,然后除以"FLASKY_COMMENTS_PER_PAGE",它就可以知道总共有多少个页面,并决定你最后要去哪一页。

    但是让我困惑的是,为什么"(post.comments.count()"需要减去1 ??

。如果评论数量是22,那么我添加了1条评论计算应该是(23-1)//FLASKY_COMMENTS_PER_PAGE + 1 ??

我真的不知道为什么要减去1....

@main.route('/post/<int:id>')
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(body = form.body.data, post = post, author = current_user._get_current_object())
        db.session.add(comment)
        flash('Your comment has been published.')
        return redirect(url_for('.post',id = post.id, page = -1))
    page = request.args.get('page',1,type=int)
    if page == -1:
        page = (post.comments.count()-1)//current_app.config['FLASKY_COMMENTS_PER_PAGE']+1
        pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
            page,per_page = current_app.config['FLASKY_COMMENTS_PER_PAGE'],
            error_out = False)
        comments = pagination.items
    return render_template('post.html',posts=[post],form = form,comments=comments,pagination = pagination)  

让我们看看这一行:

page = (post.comments.count()-1)//current_app.config['FLASKY_COMMENTS_PER_PAGE']+1

FLASKY_COMMENTS_PER_PAGE为10。页码从1开始。没有减法,当有9条评论:9//10 + 1 = 0 + 1 = 1仍然很好,但当你有10条评论:10//10 + 1 = 1 + 1 = 2。所以你有两页而不是一页。这就是为什么你需要从注释总数中减去1。

最新更新