Python Flask SQLAlchemy Pagination

user7731688 picture user7731688 · Mar 29, 2017 · Viewed 27.4k times · Source

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()

I have been looking at the following examples:

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.

Answer

mechanical_meat picture mechanical_meat · Mar 29, 2017

I recommend using Flask-SQLAlchemy's pagination: http://flask-sqlalchemy.pocoo.org/2.1/api/?highlight=pagination#flask.ext.sqlalchemy.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>