如何使用 SQLAlchemy 上下文管理器并仍然获取行 ID?

gwg*_*gwg 6 python transactions sqlalchemy contextmanager

我正在使用提供的contextmanagerSQLAlchemy来为我处理会话。我不明白的是如何获取自动生成的 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
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

z0r*_*z0r 7

使用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
Run Code Online (Sandbox Code Playgroud)

如果flush在会话超出范围之后发生异常,则更改将回滚到事务的开头。在这种情况下,您soft_file实际上不会被写入数据库,即使它已被赋予一个 ID。