数据表的外键进阶(二)


一、让User通过articles获取Article数据

1、app.py

from flask import Flask, render_template
from exts import db
from models import Article, User

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

@app.route('/')
def index():
    user = User.query.first()
    articles = user.articles
    return render_template('index.html', articles=articles)

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

2、index.html

{% for article in articles %}
  <p>{{ article.title }}</p>
{% endfor %}

二、让Article通过author获取User数据

1、app.py

from flask import Flask, render_template
from exts import db
from models import Article, User

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

@app.route('/')
def index():
    article = Article.query.first()
    user = article.author
    return render_template('index.html', user=user)

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

2、index.html

{{user.username}}

results matching ""

    No results matching ""