在我的 Pyramid+SQLAlchemy 网站上,我希望客户查看他下的所有购买。Purchase 有很多PurchaseOrder,PurchaseOrder 有很多PurchaseOrderDetail。
我想以优化的方式获取所有采购上下文(包括订单和详细信息),因此我正在研究 SQLAlchemy 加载策略。
我的模型声明如下所示:
class Purchase(Base):
__tablename__ = 'purchase'
__table_args__ = {'schema':'db','autoload':True}
customer = relationship(Customer)
billing_address = relationship(Address,primaryjoin="Address.AddressId==Purchase.BillingAddressId")
shipping_address = relationship(Address,primaryjoin="Address.AddressId==Purchase.ShippingAddressId")
orders = relationship(PurchaseOrder)
class PurchaseOrder(Base):
__tablename__ = 'purchase_order'
__table_args__ = {'schema':'db','autoload':True}
company = relationship(Company)
delivery_service = relationship(DeliveryService)
details = relationship(PurchaseOrderDetail)
class PurchaseOrderDetail(Base):
__tablename__ = 'purchase_order_detail'
__table_args__ = {'schema':'db','autoload':True}
product_variant = relationship(ProductVariant)
我想要的是这种形式的东西:
db_session = DBSession()
p = db_session.query(Purchase).\
options(joinedload_all(Purchase.customer,
Purchase.billing_address,
Purchase.shipping_address)
,subqueryload_all(Purchase.orders,
Purchase.orders.details)).all()
但是,该Purchase.orders.details
部分是不允许的并引发以下异常:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\apps\pyramid\lib\site-packages\sqlalchemy\orm\attributes.py", line 139, in __getattr__
key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'details'
所以,我的问题是:
- 查询 Purchase 模型时如何加载 PurchaseOrderDetails?
- 这是获得所有购买内容的最佳方式吗?
提前致谢