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.
User.query.options(load_only('age')).all()
User.query.with_entities(User.age).all()