[英]SQLAlchemy - Session.commit in Session.query loop resets object __dict__
When iterating over session.Query
object and calling update, I've noticed that the returned objects no longer have their __dict__
's populated. 当遍历
session.Query
对象并调用update时,我注意到返回的对象不再填充其__dict__
。
Eg 例如
foos = session.query(Foo)
for foo in foos:
print "{}".format(foo.__dict__)
foo.somefield = "somevalue"
session.add(foo)
session.commit() # The next print statement won't show anything
If any of the fields in foo
are read during the iteration, though, all of the __dict__
fields become resolved. 但是,如果在迭代过程中读取了
foo
中的任何字段,则所有__dict__
字段都会被解析。
Eg 例如
foos = session.query(Foo)
for foo in foos:
# Reading any of the fields, causes all of the fields to be resolved.
foo.somefield
print "{}".format(foo.__dict__)
foo.somefield = "somevalue"
session.add(foo)
session.commit() # The next print statement won't show anything
Is there any way to have these values appear in __dict__
without needing to read them first? 有什么方法可以让这些值出现在
__dict__
而无需先阅读它们?
The reason this happens is that SQLAlchemy automatically expires your instances after you call commit()
. 发生这种情况的原因是,SQLAlchemy在调用
commit()
之后自动使您的实例过期。 So what happens in order: 那么顺序发生了什么:
Foo
s Foo
__dict__
, works __dict__
,作品 Foo
s are expired (empties the __dict__
of all Foo
s) Foo
都已过期(清空所有Foo
的__dict__
) __dict__
, empty, oops __dict__
,空,哎呀 Reading a field will lazily re-load the instance from the database which is why that works. 读取字段将延迟从数据库中重新加载实例,这就是为什么这样做的原因。 What you want to do is to turn off expire_on_commit , eg if you use
sessionmaker
: 您要做的是关闭expire_on_commit ,例如,如果您使用
sessionmaker
:
Session = sessionmaker(expire_on_commit=False)
But be careful that naïve code may no longer do what you expect. 但是要小心,天真的代码可能不再能满足您的期望。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.