How to select_related() in Flask/SQLAlchemy?

…衆ロ難τιáo~ 提交于 2019-12-07 04:46:54

问题


Having 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 perform select_related in SQLAlchemy/Flask?

I've found in documentation that I can make something like

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

But I need first to get specific question by id and then select related to it

So I need something like this

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

Ho can I do this?


回答1:


answers = Question.query.options(joinedload(Question.answers)).get(5).answers

The expression Question.query.options(joinedload(Question.answers)).get(5) issues the query with a join and evaluates to a Question instance. Accessing answers attribute does not issue any queries.

You could also do it more explicitly

answers = Answer.query.filter_by(question_id=5).all()


来源:https://stackoverflow.com/questions/27983129/how-to-select-related-in-flask-sqlalchemy

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