Receive data from DB in sqlalchemy model, if I create a select query only with 2 of 6 columns (without unnecessary data from the remaining 4 column)

In my Fastapi project I have a table model with 6 columns. I have tried to make query for returning data only from 2 columns:

query = select(PostSQL.id, PostSQL.title)
result = await db.execute(query)
post = result.all()

I have response with list of tuples: [(1, ‘hello’), (2, ‘hello’)]

When I create a select query with:

query2 = select(PostSQL).options(load_only(PostSQL.id, PostSQL.title))

result2 = await db.execute(query2)
post2 = result2.all()
#or post2 = result2.scalar().all()

I have response data that converted to PostSQL object with data from all table columns.

  • “I have response data that converted to PostSQL object with data from all table columns.” how are you doing this? Can you explain how you arrived at this?

    – 




Leave a Comment