怎样才能得到最后插入的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
发布于 2021-04-24 15:54:08
SQLAlchemy对lastrowid的支持依赖于底层的DB-API实现,因此依赖此属性是不安全的。但是,SQLAlchemy在CursorResult
对象上提供了一个应该是可靠的inserted_primary_key属性。
返回值是插入行的主键值的元组。
问题中的这个版本的代码:
async def foo(db_session: AsyncSession, login):
r1 = await db_session.execute(statement=models_users.insert().values(login=login))
print(r1)
print('Last pk', r1.inserted_primary_key)
await db_session.flush()
await db_session.commit()
将产生如下输出:
<sqlalchemy.engine.cursor.CursorResult object at 0x7f0215966bb0>
Last pk (17,)
https://stackoverflow.com/questions/67233244
复制相似问题