neil_h_sw
neil_h_sw

Reputation: 85

Flask-SQLAlchemy: Trying to use query.paginate() in reverse order

I'm following Corey Schafer's tutorials to make a basic Flask website with SQLAlchemy (flask-sqlalchemy). The website uses a database containing users and posts. Currently, I display the posts on the front page ordered from oldest to newest, but I want to display them in the reverse order. I know I can use Session.query.all().order_by(), but I want to use the paginate method to paginate the results, and I don't know how to do that.

My original code works fine using Session.query.paginate(), but I want to reverse the results.

Currently, this is how my code looks for the home page route:

@app.route("/home")
def home(page=1):
    page = request.args.get('page', 1, type=int)
    posts = Post.query.paginate(page=page, per_page=5) # this line right here
    return render_template("home.html", posts=posts)

This code works fine to display the posts in multiple pages, but I want to reverse the results of the query so that I can display the posts in reverse order. I know about the method order_by(), but I don't know how to use it and whether I can use it with the paginate() method.

Upvotes: 4

Views: 2359

Answers (1)

rrcal
rrcal

Reputation: 3752

Your answer is yes, you can use paginate after sorting your query with order_by. As per descending order, you can just pass the method desc() to your order_by.

For example:

@app.route("/home")
def home(page=1):
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.id.desc()).paginate(page=page, per_page=5) # this line right here
    return render_template("home.html", posts=posts)

I used the columnd id, but you can sort by any column in your database.

Upvotes: 5

Related Questions