【问题标题】:Flask-SQLAlchemy: Trying to use query.paginate() in reverse orderFlask-SQLAlchemy:尝试以相反的顺序使用 query.paginate()
【发布时间】:2019-07-29 21:45:31
【问题描述】:

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

【问题讨论】:

    标签: python flask sqlalchemy flask-sqlalchemy


    【解决方案1】:

    您的回答是是的,您可以在使用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,但您可以按数据库中的任何列进行排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-01
      • 2018-07-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2016-09-20
      • 2015-02-17
      相关资源
      最近更新 更多