我正在使用 SQLAlchemy 的 provided contextmanager
为我处理 session 。我不明白的是如何获取自动生成的 ID,因为(1)直到调用 commit()
之后才创建 ID(2)新创建的实例仅在上下文管理器的范围:
def save_soft_file(name, is_geo=False):
with session_scope() as session:
soft_file = models.SoftFile(name=name, is_geo=is_geo)
session.add(soft_file)
# id is not available here, because the session has not been committed
# soft_file is not available here, because the session is out of context
return soft_file.id
我错过了什么?
最佳答案
使用session.flush()
在当前事务中执行挂起的命令。
def save_soft_file(name, is_geo=False):
with session_scope() as session:
soft_file = models.SoftFile(name=name, is_geo=is_geo)
session.add(soft_file)
session.flush()
return soft_file.id
如果在 flush
之后但在 session 超出范围之前发生异常,更改将回滚到事务的开头。在那种情况下,您的 soft_file
实际上不会写入数据库,即使它已被赋予 ID。
关于python - 如何使用 SQLAlchemy contextmanager 并仍然获得行 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28946467/