reading from joined query in flask-sqlalchemy

扶醉桌前 提交于 2020-01-24 12:43:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!