如何获取最后插入的id?
请注意sqlalchemy
版本,所以this问题不是我的情况
我试过:
async def foo(db_session: AsyncSession, login):
r1 = await db_session.execute(statement=models_users.insert().values(login=login))
r2 = await db_session.flush()
# r3 = await db_session.fetchval(...) # Error, no such method for async
r4 = await db_session.commit()
print(r2, r4, r1.fechone()) # None, None, None
print(r1.lastrowid) # 'AsyncAdapt_asyncpg_cursor' object has no attribute 'lastrowid'
SQLAlchemy 1.4.4
asyncpg 0.22.0
SQLAlchemy对lastrowid的支持取决于底层DB-API实现,因此依赖此属性是不安全的。然而,SQLAlchemy在
CursorResult
对象上提供了一个inserted_primary_key属性,这应该是可靠的返回值是插入行的主键值的元组
此版本的问题代码:
将产生如下输出:
相关问题 更多 >
编程相关推荐