父实例未绑定到Session; 属性"帐户"的延迟加载操作无法继续

mar*_*ddy 20 python sqlalchemy

在尝试执行以下操作时:

for line in blines:
    line.account = get_customer(line.AccountCode)
Run Code Online (Sandbox Code Playgroud)

我在尝试为以下值分配值时遇到错误line.account:

DetachedInstanceError: Parent instance <SunLedgerA at 0x16eda4d0> is not bound to a       Session; lazy load operation of attribute 'account' cannot proceed
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么??

zzz*_*eek 27

"已分离"表示您正在处理与a无关联的ORM对象Session.它Session是关系数据库的网关,因此,只要您在映射对象上引用属性,ORM有时需要返回数据库以获取该属性的当前值.通常,您应该只使用"附加"对象 - "已分离"是用于缓存和在会话之间移动对象的临时状态.

请参阅对象状态的快速入门,然后可能也阅读该文档的其余部分;).

  • 事实证明,我得到`DetachedInstanceError`的情况是因为会话不能以并发方式使用 - 异常因同步调用芹菜任务而被绊倒. (3认同)
  • @mcpeterson我的解决方案是避免以并发方式使用`session`,因为它不是线程安全的.见http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#is-the-session-thread-safe (2认同)

Far*_*eed 5

我在芹菜上也遇到了同样的问题。增加lazy='subquery'关系解决了我的问题。

  • 您能再说一遍吗?您是否将其添加到关系的`&lt;relationshipname&gt; = &lt;数据库名称&gt; .relationship(&lt;other model name&gt;,back_populates =“ &lt;other model's Relationship&gt;”)`的定义中? (4认同)