Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading from joined query in flask-sqlalchemy

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>
like image 482
Joost Barendregt Avatar asked Oct 20 '25 20:10

Joost Barendregt


1 Answers

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>

like image 188
Iron Fist Avatar answered Oct 22 '25 09:10

Iron Fist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!