Search code examples
pythonflaskswaggerflask-sqlalchemyflask-restful

Keyed Tuple is not returning while doing select queries with dbobject.query.with_entities(dbobject.col1,dbobject2) in Flask SqlAlchamey


I'm working in swagger with Flask application. In that i'm trying to create API response. So i tried the below stuff.

I have a table with 15 columns. I just wanted to select only particular columns from the table. So i used with_entities() from sqlalchemy like below.

dbobject.query.with_entities(dbobject.id, dbobject.name, dbobject.version)

It is returning the available rows from table in this format for all rows (21, asset21, 9898) but not as keyed tuple. Also row.__table__.columns.keys() is not working when i tried to get column names for selected rows from the returned rows of above query. It just endup with below error

    for col in row.__table__.columns.keys() if col != 'id')
AttributeError: 'result' object has no attribute '__table__'

But row.__table__.columns.keys() the same snippet is working when i do select all columns from table dbobject.query.all()

Any specific reason why it is not working for with_entities?


Solution

  • Try Labeling should give the end result as expected

    dbobject.query.with_entities(dbobject.id.label('id'), dbobject.name.label('name'), dbobject.version.label('version'))