sqlalchemy(1.4 版!)——获取最后插入的 ID

sqlalchemy (vesrion 1.4 !) - get last inserted id

如何获取最后插入的 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 对 CursorResult 对象的 lastrowid depends on the underlying DB-API implementation, so it isn't safe to rely on this attribute. However SQLAlchemy provides an inserted_primary_key 属性的支持应该是可靠的。

return 值是插入行的主键值的元组。

本题代码版本:

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,)