如何在Flask / SQLAlchemy中select_related()? [英] How to select_related() in Flask/SQLAlchemy?
问题描述
class问题(db.Model):
id = db.Column(db .Integer(),primary_key = True)
title = db.Column(db.String(125))
text = db.Column(db.Text())
answers = db。关系('答案',backref ='for_question')
class答案(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'))
如何在SQLAlchemy / Flask中执行select_related?
在文档中发现,我可以做一些像
session.query(Question).options(joinedload(Question.aswers))
但是我需要首先通过id来获得具体的问题,然后选择相关的问题。
所以我需要这样的东西
Question.query.get(5).select_related()
(5).answers
表达式 Question.query.options(joinedload(Question.answers))。get(5)
使用连接发出查询并计算为问题
实例。访问答案
属性不会发出任何查询。您也可以更明确地做到这一点
answers = Answer.query.filter_by(question_id = 5).all()
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?
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()
这篇关于如何在Flask / SQLAlchemy中select_related()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!