我试图从有关将模型映射到任意表的文档中复制代码,但出现以下错误:
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.
这是我实现代码示例的方式。
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
我可以使用以下方法完成这项工作:
class Customer(Base):
__table__ = customer_select.alias()
不幸的是,这会在子选择中创建所有查询,这非常慢。
有没有办法将模型映射到任意选择?这是文档错误吗?文档中的代码示例对我不起作用(在 sqlalchemy==0.8.0b2 或 0.7.10 中)