from sqlalchemy import select, update
# 方式一
async def update_record(model):
async with async_session() as session:
async with session.begin():
result = await session.execute(select(model).where(id=1))
now = result.scalars().first()
if now is None:
raise Exception("记录不存在")
now.name = "李四"
now.age = 23
# 这里测试过,如果去掉flush会导致数据不更新
await session.flush()
session.expunge(now)
return now
# 方式二
async def update_by_map():
async with async_session() as session:
async with session.begin():
# 更新id为1的数据,并把name改为李四 age改为23
sql = update(model).where(model.id == 1).values(name="李四", age=23)
await session.execute(sql)
删除
删除的话,软删除大家都是update,所以不需要多说,物理删除的话,也有两种方式:
查到以后删除之
直接根据条件删除(这种我没有仔细研究,我选的是第一种方式,容错率高点)
async def delete_by_id():
async with async_session() as session:
async with session.begin():
result = await session.execute(select(model).where(model.id == 2))
original = result.scalars().first()
if original is None:
raise Exception("记录不存在")
# 如果是多条
# session.delete(original)
# for item in result:
# session.delete(item)