我试图让人们关注工作,但是对于经典的"调用循环中的数据库项目"问题,即
users = Session.query(User).all() # SELECT * from users
for user in users:
foo(user.exams) # SELECT * from exams where user_id = ?
为了加急,我在做什么。
首先,这是我的模型定义:
Base = declarative_base()
class Users(Base):
id = db.Column(db.Integer, primary_key=True)
class Exams(Base):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
user = db.relationship(
"Users",
backref=sqlalchemy.orm.backref(
'exams',
cascade='all, delete-orphan'
),
foreign_keys=[user_id]
)
但是,当我实际检查原始sql时:
q = Session().query(Users).join(Users.exams).options(joinedload(Users.exams))
print str(q)
我得到(格式化):
(SELECT users.id
FROM users
JOIN exams ON users.id = exams.user_id)
当我真的在期待:
(SELECT exams.id, exams.user_id, users.id
FROM users
JOIN exams ON users.id = exams.user_id)
这样我就可以user.exams
而不向数据库发送另一个查询。如何使eagerloading工作?
答案 0 :(得分:1)
应该只是:
q = Session().query(Users).options(joinedload('exams'))