Skip to main content
 首页 » 编程设计

python之Flask-SQLAlchemy:尝试以相反的顺序使用 query.paginate()

2024年11月24日8lautakyan007

我正在按照 Corey Schafer 的教程使用 SQLAlchemy (flask-sqlalchemy) 制作一个基本的 Flask 网站。该网站使用包含用户和帖子的数据库。目前,我在首页上按从旧到新的顺序显示帖子,但我想以相反的顺序显示它们。我知道我可以使用 Session.query.all().order_by(),但我想使用分页方法对结果进行分页,但我不知道该怎么做。 p>

我的原始代码使用 Session.query.paginate() 运行良好,但我想反转结果。

目前,这是我的代码查找主页路由的方式:

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

此代码可以很好地在多个页面中显示帖子,但我想反转查询的结果,以便我可以以相反的顺序显示帖子。我知道 order_by() 方法,但我不知道如何使用它以及是否可以将它与 paginate() 方法一起使用。

请您参考如下方法:

您的回答是是,您可以在使用order_by 对查询进行排序后使用分页。按照降序,您只需将方法 desc() 传递给您的 order_by。

例如:

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

我使用了 id 列,但您可以按数据库中的任何列进行排序。