2016-09-30 57 views
0

我學習瓶Web開發的書,並在第13章,它是關於的Python瓶分頁配方

後的路由功能是作爲下面的「博客文章評論」,書中說:「當頁= -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) 

回答

1

讓我們來看看這條線:

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。所以你得到2頁而不是1.這就是爲什麼你需要從總評論中減去1。

+0

啊....我知道了...它避免了當評論數量是每頁設置次數時的錯誤....非常感謝...哈哈有一個愉快的週末 – NoDinner