【问题标题】:Query db SQLAlchemy starting on last index [duplicate]从最后一个索引开始查询 db SQLAlchemy [重复]
【发布时间】:2019-04-08 04:35:55
【问题描述】:

我有以下问题:

我目前正在学习 Flask 和 SQLAlchemy,在我的环境中我正在构建一个博客(一个简单的博客)。在我的家乡路线上,我正在执行以下操作:

@app.route("/")
@app.route("/home")
def home():
    posts = Post.query.all()
    return render_template("home.html", title = "Home", posts = posts)

posts = Post.query.all() 将查询我的 Posts 表上的所有字段,然后在我的模板上执行以下操作:

{% extends "layout.html" %}

    {% block content %}

        {% for post in posts %}

            <article class="media content-section">
                <img class="rounded-circle account-img" src="{{ 
                url_for("static", filename="profile_pics/" + post.author.image_file) }}" alt="">
                <div class="media-body">
                    <div class="article-metadata">
                        <a class="mr-2" href="#">{{ post.author.username }}</a>
                        <small class="text-muted">{{ post.date_posted.strftime("%Y-%m-%d") }}</small>
                    </div>
                    <h2><a class="article-title" href="#">{{ post.title }}</a></h2>
                    <hr>
                </div>
            </article>

        {% endfor %}


{% endblock %}

问题是,在这个 for 循环中,我的最新帖子显示为最后一个帖子,当我真的想把它作为第一个帖子时,我如何通过 SQLAlchemy 和 Flask 反向查询数据库,或者我是想错了吗?

【问题讨论】:

    标签: python python-3.x flask sqlalchemy flask-sqlalchemy


    【解决方案1】:

    使用 SQLAlchemy 的 order_by

    Post.query.order_by(desc(Post.date_posted)).all()
    

    例子:

    >>> from datetime import datetime
    >>> p1 = Post(posted=datetime.strptime('2018-01-01', '%Y-%m-%d'))
    >>> p2 = Post(posted=datetime.strptime('2017-01-01', '%Y-%m-%d'))
    >>> p3 = Post(posted=datetime.strptime('2019-01-01', '%Y-%m-%d'))
    >>> db.session.add_all([p1, p2, p3])
    >>> db.session.commit()
    >>> Post.query.order_by(desc(Post.posted)).all()
    [<Post 3>, <Post 1>, <Post 2>]
    >>> [item.posted.year for item in Post.query.order_by(desc(Post.posted)).all()]
    [2019, 2018, 2017] #most recent to oldest
    

    【讨论】:

    • 很好,谢谢,我试试看。
    • 嘿,看来这就是要走的路,但问题是在我导入 desc 后我收到一条错误消息,提示 flask_sqlalchemy 无法导入 desc。我猜 desc 在 sqlalchemy 中,但在 Flask-SQLAlchemy 库中没有,这可能吗?
    • 好的,看起来flask-sqlalchemy包也获取了sqlalchemy,但是desc不能从flask-sqlalchemy导入,它必须直接从sqlachemy导入:` from sqlalchemy import desc`
    • from sqlalchemy import desc 或直接Post.query.order_by(Post.date_posted.desc()).all()
    猜你喜欢
    • 2022-11-03
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2011-02-09
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多