简体   繁体   English

SQLAlchemy-Session.query循环中的Session.commit重置对象__dict__

[英]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: 那么顺序发生了什么:

  1. you load all Foo s 您加载所有Foo
  2. print __dict__ , works 打印__dict__ ,作品
  3. commit 承诺
  4. all Foo s are expired (empties the __dict__ of all Foo s) 所有Foo都已过期(清空所有Foo__dict__
  5. print __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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM