I tried to replicate the code from the docs regarding mapping models to arbitrary tables, but I get the following error:
sqlalchemy.exc.InvalidRequestError: When mapping against a select() construct, map against an alias() of the construct instead.This because several databases don't allow a SELECT from a subquery that does not have an alias. Here is how I implemented the code example.
from sqlalchemy import ( select, func, Table, Column, Integer, ForeignKey, MetaData, ) from sqlalchemy.ext.declarative import declarative_base metadata = MetaData() Base = declarative_base() customers = Table('customer', metadata, Column('id', Integer, primary_key=True), ) orders = Table('order', metadata, Column('id', Integer, primary_key=True), Column('price', Integer), Column('customer_id', Integer, ForeignKey('customer.id')), ) subq = select([ func.count(orders.c.id).label('order_count'), func.max(orders.c.price).label('highest_order'), orders.c.customer_id ]).group_by(orders.c.customer_id).alias() customer_select = select([customers,subq]).\ where(customers.c.id==subq.c.customer_id) class Customer(Base): __table__ = customer_select I can make this work by using the following:
class Customer(Base): __table__ = customer_select.alias() Unfortunately, that creates all the queries in a subselect, which is prohibitively slow.
Is there a way to map a model against an arbitrary select? Is this a documentation error--the code sample from the docs doesn't work for me (in sqlalchemy==0.8.0b2 or 0.7.10)