I'am working with alchemy ORM's Query object. In different context it returns different types.
I have following table in postgres:
select * from test;
test_id | test_col1 | test_col2
---------+-----------+-----------
1 | ABC | ABC
2 | XYZ | XYZ
I have following class in Python3:
class Test (DeclarativeBase):
__tablename__ = 'test'
id = sa.Column('test_id', sa.Integer(), primary_key=True)
col1 = sa.Column('test_col1', sa.String(250), nullable = True)
col2 = sa.Column('test_col2', sa.String(250), nullable = True)
My queries and results:
In [2]: q1 = session.query(Test)
In [3]: rows1 = q1.all()
In [4]: print(type(rows1[0]))
<class '__main__.Test'>
In [5]:
In [5]: cte = session.query(Test).cte()
In [6]: q2 = session.query(cte)
In [7]: rows2 = q2.all()
In [8]: print(type(rows2[0]))
<class 'sqlalchemy.util._collections.result'>
In [9]:
In [9]: q3 = session.query(Test).filter(Test.col1 == 'ABC')
In [10]: rows3 = q3.all()
In [11]: print(type(rows3[0]))
<class '__main__.Test'>
In [12]:
In [12]:
In [12]: q4 = session.query(Test).filter(Test.col1 == 'ABC').one()
In [13]: print(type(q4))
<class '__main__.Test'>
In [14]:
In [14]: result = session.execute(session.query(Test).filter(Test.col1 == 'ABC'))
In [15]: for row in result:
...: print (type(row))
...:
<class 'sqlalchemy.engine.result.RowProxy'>
Only type "sqlalchemy.util._collections.result" allows use method _asdict() on row. So, if I call _asdict() in my code, I must explicitly check type, otherwise - I get 'AttributeError' exception.
Is it possible to return only one type from alchemy ORM query and use _asdict() no additional checks?