如何使用SQLAlchemy contextmanager并仍然获得行ID?

2024-03-29 02:19:10 发布

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

我正在使用SQLAlchemy的provided ^{}为我处理会话。我不明白如何获得自动生成的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

我错过了什么?在


Tags: thenameidheresqlalchemyissessionnot
1条回答
网友
1楼 · 发布于 2024-03-29 02:19:10

使用^{}在当前事务中执行挂起的命令。在

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之后但在会话超出范围之前发生异常,则更改将回滚到事务的开始。在这种情况下,soft_file实际上不会写入数据库,即使它已经被赋予了一个ID

相关问题 更多 >