How to get all list of id with specific properties in sqlalchemy async

Viewed 266

Hey I am trying to learn sqlalchemy but I am stucked at getting list of all User id whose state is ON. The query does not work in async sqlalchemy.

I tried this but it does not work.

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() 
2 Answers

You can use all() to retrieve all rows in a list:

    ...
    async with async_session() as session:
        result = await session.execute(stmt)
        return result.all() 

the correct code

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()]
Related