We have an application which uses sqlalchemy
as ORM. Apart from mapping tables, we also use it to map existing database views, which works fine.
However, we cannot find an easy way to map custom queries to Models. For example, let's say we have a report like:
q = session.query(
Table1.field1, Table2.field2, func.sum(Table2.field3).label('sum')
).join(
Table2, Table1.id == Table2.id
).filter(
Table1.field1 == param1, Table1.field2 == param2
).group_by(
Table1.field1, Table2.field2
)
We would like to map this query to a class like
class Report(CustomBaseModel):
field1 = Column(Integer, primary_key=True)
field2 = Column(Integer, primary_key=True)
sum = Column(Numeric)
Our CustomBaseModel
has a lot of functionality already implemented, so being able to use it here would lead to less code duplication. For instance, using the declarative base this way would make it possible to define relationship
s with to other tables.
Of course this example doesn't work because there is no selectable "report"
in the database.
I tried setting __table__ = q.subquery()
in the Report
class. This way the query works but it is not possible to define columns, relationships or other properties. Perhaps there is a better way to achieve this.