Python Flask SQLAlchemy分页 [英] Python Flask SQLAlchemy Pagination

查看:397
本文介绍了Python Flask SQLAlchemy分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过Flask-SQLAlchemy或Flask-Pagination来实现分页,或者.我不确定如何初始化分页,设置页面,确定页面,异常等.我来自PHP,这对Python来说还很陌生.

I am having trouble implementing pagination with Flask-SQLAlchemy or Flask-Pagination, either or. I am unsure how to initialize the pagination, setting pages, determining pages, offest, etc. I am coming from PHP, quite new to Python.

我正在查询数据库中的所有帖子

I am querying all the posts in my database

posts = Posts.query.order_by(Posts.time.desc()).all()

我一直在看以下示例:

  • http://www.ergo.io/tutorials/better-pagination-in-flask/better-pagination-in-flask/
  • https://pythonhosted.org/Flask-paginate/
  • sqlalchemy pagination

我对真正的工作感到困惑,我发现的信息在文章之间有很大的不同.这让我感到困惑,不知道从哪里开始.我想查询数据库表的所有行,将结果限制为20并分页.我没有清楚地看到这一点.

I am confused on really what to do, the information I am finding greatly differs between articles. It's left me with confusion and not knowing where to begin. I want to query all rows of the database table, limit the results to 20 and paginate. I'm not seeing this clearly.

推荐答案

我建议使用Flask-SQLAlchemy的分页:

I recommend using Flask-SQLAlchemy's pagination: http://flask-sqlalchemy.pocoo.org/2.1/api/?highlight=pagination#flask.ext.sqlalchemy.Pagination

这里有一个写得很好的示例: https: //blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ix-pagination

There's a well-written example here: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ix-pagination

以下是该视图的基本概念:

Here's the basic idea for the view:

@app.route('/myview/<int:page>',methods=['GET'])
def view(page=1):
    per_page = 10
    posts = Posts.query.order_by(Posts.time.desc()).paginate(page,per_page,error_out=False)
    return render_template('view.html',posts=posts)

然后是模板(我不知道您的帖子模型,所以我做了一些事情):

And then for the template (I don't know your posts model so I made something up):

<html>
  <head>
    Posts
  </head>
  <body>

{% for post in posts.items %}
<p>
  {{ post.post_name }} post body: <b>{{ post.body }}</b>
</p>
{% endfor %}
{% if posts.has_prev %}<a href="{{ url_for('view', page=posts.prev_num) }}">&lt;&lt; Newer posts</a>{% else %}&lt;&lt; Newer posts{% endif %} | 
{% if posts.has_next %}<a href="{{ url_for('view', page=posts.next_num) }}">Older posts &gt;&gt;</a>{% else %}Older posts &gt;&gt;{% endif %}

  </body>
</html>

这篇关于Python Flask SQLAlchemy分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆