sqlalchemy - 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'
那么默认解决方案是什么
解决方案
推荐阅读
- sql - 如何使用游标从oracle数据库中检索数据?
- javascript - 如何使用 jquery / JS 从 td 获取我的 ID 和两个文本框的值
- php - Symfony 3 - 在我的模式中传递错误的变量
- android - Drawable 未在画布中完全绘制
- jquery - 如何在联系表格中至少填写一个字段
- ios - 如何检测文本是否修复?
- android - 两个文本视图中具有不同值的分隔逗号的字符串的逻辑
- python - 如何在python中重命名文本文件?
- asp.net-mvc - JwtAuthentication disabled 身份登录
- java - 如何使段落标签内的锚标签可点击?