SQLAlchemy db session外部的访问表对象

2024-06-16 12:28:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码片段可以对表Customer进行操作:

with session.begin(subtransactions=True):
    db_obj = Customer(...)

result = io_processing() # may cause greenlet switching

# I do not want to make it inside the transaction above,
# Because some legacy I/O related code which will causes greenlet switching
if result:
    self.read_write_db(session, db_obj)

在读写功能中:

^{pr2}$

将事务外部的“db_obj”传递到另一个函数是否安全?在

或者我必须在读写数据库中再次查询db_obj并更新它?在


Tags: 代码iotrueobjdbsessionwithcustomer
1条回答
网友
1楼 · 发布于 2024-06-16 12:28:41

是的,这是可能的,但是您必须通过在read_write_db的会话中合并db_obj来获得一个新实例。在

with session.begin(subtransactions=True):
    merged_db_obj = session.merge(db_obj)
    # work with merged_db_obj ...

有关所有详细信息,请参见http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#merging。合并可能很棘手。在

相关问题 更多 >