问题
After successfully joining two db tables, I'm trying to read the data from the 2nd table by addressing the first. I'm addressing opinion.topic_name
from my jinja2 template, but nothing is returned.
How can I access the Topic.topic_name value from the joined query?
view
@main.route('/', methods=['GET', 'POST'])
def index():
form = IndexForm()
opinions = []
if form.validate_on_submit():
opinions = Opinion.query
.filter_by(party_id=form.party.data)
.filter_by(topic_id=form.topic.data)
.join('topic')
.all()
return render_template('index.html', form=form, opinions=opinions)
model
class Opinion(db.Model):
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(2000))
topic_id = db.Column(db.Integer, db.ForeignKey('topic.id'))
party_id = db.Column(db.Integer, db.ForeignKey('party.id'))
class Topic(db.Model):
id = db.Column(db.Integer, primary_key=True)
topic_name = db.Column(db.String(64))
opinions = db.relationship(Opinion, backref='topic')
template (jinja2)
<div>
{{ wtf.quick_form(form) }}
</div>
<div>
{% for opinion in opinions %}
<div class='jumbotron'>
<h1>{{ opinion.topic_name }}</h1>
<p>{{ opinion.text }}</p>
</div>
{% endfor %}
</div>
回答1:
This query:
opinions = Opinion.query
.filter_by(party_id=form.party.data)
.filter_by(topic_id=form.topic.data)
.join(Topic)
.all()
will return a list of Opinion models and since in your relationship in Topic
model, you defined it as:
opinions = db.relationship(Opinion, backref='topic')
Then, in your jinja2 template, to access Topic.topic_name
, you should do:
<h1>{{ opinion.topic.topic_name }}</h1>
来源:https://stackoverflow.com/questions/41649124/reading-from-joined-query-in-flask-sqlalchemy