6

在我的 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'

所以,我的问题是:

  1. 查询 Purchase 模型时如何加载 PurchaseOrderDetails?
  2. 这是获得所有购买内容的最佳方式吗?

提前致谢

4

2 回答 2

13

subqueryload_all功能自 0.9 版起已弃用。

改为使用方法链接subqueryload

from sqlalchemy.orm import subqueryload

session.query(MyClass).options(
    subqueryload("someattribute").subqueryload("anotherattribute")
)
于 2015-09-25T00:39:22.597 回答
6

subqueryload_all(...)将查询的一部分更改为以下两个选项之一将完成这项工作:

# option-1:
subqueryload_all(
    'orders.details', # @note: this will load both *orders* and their *details*
    )

# option-2:
subqueryload_all(
    Purchase.orders,       # @note: this will load orders
    PurchaseOrder.details, # @note: this will load orders' details
    )

在列出的示例中,关于此的文档sqlalchemy.orm.subqueryload_all非常清楚。

于 2012-10-03T19:04:19.473 回答