在SQLAlchemy中的session.commit()之后更新对象



在发布session.commit()后更新对象是否正确?还是需要刷新对象?

我认为这对这个问题已经足够了,但如果需要,我可能会提供更多的信息来澄清我的问题。

编辑:

通过更新,我的意思是设置一些属性,即对象的列值。

简短的回答:不,您不需要手动刷新,sqlalchemy将为您完成。


知道它何时发生是很有用的,所以下面是简短的概述。Session.commit()的文档:

默认情况下,Session也会在所有数据库加载状态下过期事务提交后orm管理的属性。这是为了后续操作将从数据库加载最新的数据。可以使用expire_on_commit=False选项禁用此行为

基本上,给定您没有设置expire_on_commit=False,对象将自动刷新,只要您尝试访问(读取,而不是设置)session.commit()之后的属性。

my_obj = session.query(MyType).get(1)
my_obj.field1 = 'value1'
session.commit() # will commit and expire my_obj
my_obj.field1 = 'new value' # object is still the same, but field is updated
print my_obje.field1 # at this point SA will first refresh the object from the database; and make sure that new values for changed fields are applied

事实上,如果您启用日志记录,您将看到sqlalchemy在您访问(读取)持久实例的属性时发出新的SELECT语句。

最新更新