Python 父实例未绑定到会话;属性“帐户”的延迟加载操作无法继续
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13967093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parent instance is not bound to a Session; lazy load operation of attribute ’account’ cannot proceed
提问by maruthi reddy
While trying to do the following operation:
在尝试执行以下操作时:
for line in blines:
line.account = get_customer(line.AccountCode)
I am getting an error while trying to assign a value to line.account:
尝试为 分配值时出现错误line.account:
DetachedInstanceError: Parent instance <SunLedgerA at 0x16eda4d0> is not bound to a Session; lazy load operation of attribute 'account' cannot proceed
Am I doing something wrong??
难道我做错了什么??
回答by zzzeek
"detached" means you're dealing with an ORM object that is not associated with a Session. The Sessionis the gateway to the relational database, so anytime you refer to attributes on the mapped object, the ORM will sometimes need to go back to the database to get the current value of that attribute. In general, you should only work with "attached" objects - "detached" is a temporary state used for caching and for moving objects between sessions.
“分离”意味着您正在处理一个与Session. 它Session是关系数据库的网关,因此无论何时引用映射对象上的属性,ORM 有时都需要返回数据库以获取该属性的当前值。通常,您应该只处理“附加”对象——“分离”是用于缓存和在会话之间移动对象的临时状态。
See Quickie Intro to Object States, then probably read the rest of that document too ;).
请参阅Quickie Intro to Object States,然后也可能阅读该文档的其余部分;)。
回答by Farsheed
I had the same problem with Celery. Adding lazy='subquery'to relationship solved my problem.
我对芹菜有同样的问题。添加lazy='subquery'关系解决了我的问题。
回答by Devy
I encountered this type of DetachedInstanceErrorwhen I prematurely close the query session (that is, having code to deal with those SQLAlchemy model objects AFTER the session is closed). So that's one clue to double check no session closure until you absolutely don't need interact with model objects, I.E. some Lazy Loaded model attributes etc.
我DetachedInstanceError在过早关闭查询会话时遇到了这种类型(即,在会话关闭后使用代码处理那些 SQLAlchemy 模型对象)。所以这是仔细检查没有会话关闭的一个线索,直到你绝对不需要与模型对象交互,IE 一些延迟加载的模型属性等。
回答by Timo
I had the same problem when unittesting.
我在单元测试时遇到了同样的问题。
The solution was to call everything within the "with" context:
解决方案是在“with”上下文中调用所有内容:
with self.app.test_client() as c:
res = c.post('my_url/test', data=XYZ, content_type='application/json')
Then it worked.
然后它起作用了。
Adding the lazy attribute didn't work for me.
添加惰性属性对我不起作用。

