How to select_related () in Flask / SQLAlchemy?

Having the following models:

 class Question(db.Model):
   id = db.Column(db.Integer(), primary_key=True)
   title = db.Column(db.String(125))
   text = db.Column(db.Text())
   answers = db.relationship('Answer', backref='for_question')


class Answer(db.Model):
  id = db.Column(db.Integer(), primary_key=True)
  text = db.Column(db.Text())
  question_id = db.Column(db.Integer(), db.ForeignKey('question.id'))

How can I execute select_related in SQLAlchemy / Flask?

I found in the documentation that I can do something like

session.query(Question).options(joinedload(Question.aswers))

But I need to first ask a specific question by id, and then select the one related to it

So I need something like this

Question.query.get(5).select_related()

Ho can I do this?

+4
source share
1 answer
answers = Question.query.options(joinedload(Question.answers)).get(5).answers

The expression Question.query.options(joinedload(Question.answers)).get(5)issues a connection request and evaluates the instance Question. Access to the attribute answersdoes not cause any requests.

You can also do this more explicitly.

answers = Answer.query.filter_by(question_id=5).all()
+3
source

All Articles