Search code examples
pythonsqlalchemyasyncpg

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


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

Solution

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