Home > other >  get only single field data using flask session query
get only single field data using flask session query

Time:11-10

for example I have a database table Named User having following fields id , name, age now I want to get only data of field age currently I am getting data of all fields in query . how I can only get data of just one filed ?

session.query(User)
        .filter_by(
            id=1,
        )
        .all() 

CodePudding user response:

mention the column name you want in the query:

rows = session.query(User.age).filter_by(id=1).all() 

Actually SqlAlchemy queries for attributes return KeyedTuples which behave like a named tuple.

that's why your data look like that, you can access them by index or name :

rows = [i[0] for i in rows]
#or 
rows = [i.age for i in rows]

rows

read more about KeyedTuple here.

CodePudding user response:

You can use the following two statements to reduce the columns to your requirements.

load_only:

User.query.options(load_only('age')).all()

with_entities:

User.query.with_entities(User.age).all()
  • Related