我正在使用sqlalchemy,并渴望使用select in加载子类,但是在关闭会话之后,无法使用已加载的对象。
我有一个CorrelationSet类,该类具有相关列表和一个Broker。读取这些代码如下。
def read(self, coefficient=None):
'''
Read last correlation set and all associated correlations
'''
# Get last correlation set
session = Session()
query = session \
.query(func.max(CorrelationSet.time)
.label("last_date"))
lastDate = query.one().last_date
# Get broker
broker = BrokerDAO().read()
# Get correlations
query = session \
.query(CorrelationSet) \
.filter(CorrelationSet.brokerId == broker.ID) \
.filter(CorrelationSet.time == lastDate)
correlationSet = query.one()
if coefficient is not None:
correlationSet = correlationSet.subset(coefficient)
session.close()
return correlationSet
使用JupyterNotebook,我已经测试过此读取方法确实使用以下代码将代理附加到CorrelationSet:
from aitrader.dao.CorrelationSetDAO import CorrelationSetDAO
from aitrader.model.CorrelationSet import CorrelationSet
cset = CorrelationSetDAO().read(80)
broker = cset.broker
print(broker)
输出如下,表明代理已加载。
福汇
问题是,当我稍后尝试在代码中访问Broker类时,出现附件实例错误。
DetachedInstanceError:父实例未绑定到Session;的延迟加载操作 属性“经纪人”无法继续执行(此错误的背景位于: http://sqlalche.me/e/bhk3)
我不确定为什么会发生这种情况,因为我希望代理在使用selectin加载时可以使用。这里的CorrelationSet类的相关部分:
class CorrelationSet(Base):
__tablename__ = 'correlation_set'
ID = Column("correlation_set_id", BigInteger, primary_key=True)
brokerId = Column("broker_id", BigInteger, ForeignKey('broker.broker_id'))
broker = relationship("Broker", lazy='selectin')
correlations = relationship("Correlation", lazy='selectin')
time = Column("correlation_date", DateTime)