【问题标题】:sqlalchemy (vesrion 1.4 !) - get last inserted idsqlalchemy (version 1.4 !) - 获取最后插入的 id
【发布时间】:2021-04-23 15:57:07
【问题描述】:

如何获取最后插入的 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

【问题讨论】:

  • 您对缺少的 fetchval 方法有疑问吗?我认为在任何 sqlalchemy 版本中都不是这样。

标签: python sqlalchemy asyncpg


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    相关资源
    最近更新 更多