如何从SqlAlchemy查询急切加载对象?

时间:2014-06-09 07:10:38

标签: python sqlalchemy

我尝试在我的查询中设置多个选项,例如:

session.query(CatalogueEntry)\
        .options(eagerload_all())\
        .filter(CatalogueEntry.source_path.in_(paths)).all()

但我一直都有错误:

...
File "/venv/lib/python2.7/site-packages/sqlalchemy/orm/__init__.py", line 245, in eagerload_all
return joinedload_all(*args, **kwargs)
File "/venv/lib/python2.7/site-packages/sqlalchemy/orm/strategy_options.py", line 665, in joinedload_all
_UnboundLoad.joinedload, keys, True, kw)
File "/venv/lib/python2.7/site-packages/sqlalchemy/orm/strategy_options.py", line 315, in _from_keys
opt = meth(opt, all_tokens[-1], **kw)
IndexError: list index out of range

如果我将其更改为:

session.query(CatalogueEntry)\
        .options(eagerload_all('*'))\
        .filter(CatalogueEntry.source_path.in_(paths)).all()

我明白了:

DetachedInstanceError: Instance <CatalogueEntry at 0x1026936d0> is not bound to a Session; attribute refresh operation cannot proceed

我想从会话中分离我的对象并将它们传递回只读取属性的客户端代码。在我添加选项之前,我收到了DetachedInstanceErrors。

如何从sqlalchemy(0.9.4)查询中返回完全水合的对象,在会话结束后,我的代码的其他部分可以读取其属性?

1 个答案:

答案 0 :(得分:4)

session.query(CatalogueEntry)\
        .options(joinedload('name_of_relationship_attribute'))\
        .filter(CatalogueEntry.source_path.in_(paths)).all()

还有子查询

您还可以使用lazy ='joined'或lazy ='subquery'设置关系定义中的默认加载方法

请参阅此网址以供参考 http://docs.sqlalchemy.org/en/rel_0_9/orm/loading.html?highlight=joinedload#sqlalchemy.orm.joinedload_all