首页 > 解决方案 > sqlalchemy 获取最后插入的 ID|创建的记录(asyncpg 适配器)

问题描述

我知道这个问题被问过很多次了,但是现在sqlalchemy有了新的版本和语法,所以这些答案主要是过时的

#SQLAlchemy        1.4.4
#asyncpg           0.22.0
#PostgreSQL 12.6


from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from fastapi import Depends


engine = create_async_engine(url=config.SQLALCHEMY_PG_ASYNC_URL, echo=False, future=True)
async_session = sessionmaker(bind=engine, autoflush=True, expire_on_commit=False, class_=AsyncSession)


async def get_db():
    session = async_session()
    try:
        yield session
        await session.commit()
    except SQLAlchemyError as ex:
        await session.rollback()
        raise ex
    finally:
        await session.close()


async def foo(postgres_session: AsyncSession = Depends(database.get_db)):
    r = await postgres_session.execute(models.users.insert().values(full_name='s',
                                                                    phone_number='s',
                                                                    hashed_password='s'))
    await postgres_session.flush()
    await postgres_session.commit()
    return r

我试过: print(r.fetchone()) # None r.lastrowid # AttributeError: 'AsyncAdapt_asyncpg_cursor' 对象没有属性 'lastrowid'

那么默认解决方案是什么

标签: sqlalchemyasyncpg

解决方案


推荐阅读