SQLAlchemy:通过joinedload技术

时间:2016-09-07 10:56:33

标签: python sqlalchemy

这是我的查询。

query = dbsession.query(Parent)\
    .options(joinedload(Parent.child))\
    .first()

模型Child可通过Parent.child关系获得,并已将列名为'列'。如何使用上面列出的查询来推迟和加载该列?

1 个答案:

答案 0 :(得分:2)

通过

连接加载链接undefer选项
In [3]: class A(Base):
   ...:     __tablename__ = 'a'
   ...:     id = Column(Integer, primary_key=True)
   ...:     

In [4]: class B(Base):
   ...:     __tablename__ = 'b'
   ...:     id = Column(Integer, ForeignKey('a.id'), primary_key=True)
   ...:     value = deferred(Column(Integer))
   ...:     a = relationship('A', backref='bs')
   ...:

请参阅"Loading Along Paths"loaders上的文档。

鉴于以下模型:

value

不推荐In [21]: print(session.query(A).options(joinedload(A.bs).undefer('value'))) SELECT a.id AS a_id, b_1.value AS b_1_value, b_1.id AS b_1_id FROM a LEFT OUTER JOIN b AS b_1 ON a.id = b_1.id

In [17]: print(session.query(A).options(joinedload(A.bs)))
SELECT a.id AS a_id, b_1.id AS b_1_id 
FROM a LEFT OUTER JOIN b AS b_1 ON a.id = b_1.id

--save