查询数据库进阶(一)


使用order_by对数据进行排序

# app.py
from flask import Flask, render_template
from exts import db
from models import Article

app = Flask(__name__)
app.config.from_pyfile('config.py')
db.init_app(app)

@app.route('/')
def index():
    # 正序
    # articles = Article.query.order_by(Article.time)
    # 倒序
    articles = Article.query.order_by(Article.time.desc())
    return render_template('index.html', articles=articles)

if __name__ == '__main__':
    app.run()

# index.html
{% for article in articles %}
  <p>标题:{{ article.title }} 时间:{{ article.time }}</p>
{% endfor %}

results matching ""

    No results matching ""