【问题标题】:How to get all list of id with specific properties in sqlalchemy async如何在sqlalchemy async中获取具有特定属性的所有id列表
【发布时间】:2021-09-01 00:29:47
【问题描述】:
嘿,我正在尝试学习 sqlalchemy,但我一直在获取状态为 ON 的所有用户 ID 的列表。该查询在异步 sqlalchemy 中不起作用。
我试过了,但它不起作用。
async def free_user():
stmt = select(User).where(User.state =='ON')
async with async_session() as session:
result = await session.execute(stmt)
return result.first()
【问题讨论】:
标签:
python
sqlalchemy
asyncpg
【解决方案1】:
您可以使用all() 到retrieve all rows in a list:
...
async with async_session() as session:
result = await session.execute(stmt)
return result.all()
【解决方案2】:
正确的代码
async def free_user():
stmt = select(User).where(User.state == 'ON')
async with async_session() as session:
result = await session.execute(stmt)
return [user.user_id for user in result.scalars()]