本文介绍了从flask-sqlalchemy中的联接查询中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在成功连接两个数据库表之后,我试图通过寻址第一个表来从第二个表中读取数据.我正在从jinja2模板中寻址opinion.topic_name,但未返回任何内容.如何从加入的查询中访问Topic.topic_name值?

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?

@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)

模型

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')

模板(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>

推荐答案

此查询:

opinions = Opinion.query
                    .filter_by(party_id=form.party.data)
                    .filter_by(topic_id=form.topic.data)
                    .join(Topic)
                    .all()

将返回Opinion模型的列表,并且由于在Topic模型中的关系中,您将其定义为:

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')

然后,在jinja2模板中访问Topic.topic_name,您应该执行以下操作:

Then, in your jinja2 template, to access Topic.topic_name, you should do:

<h1>{{ opinion.topic.topic_name }}</h1>

这篇关于从flask-sqlalchemy中的联接查询中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 10:22