如何在SQLAlchemy中加载嵌套关系?

时间:2012-10-02 21:39:37

标签: python orm sqlalchemy lazy-loading

在我的Pyramid + SQLAlchemy网站上,我希望客户查看他已经放置的所有商品。购买有许多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. 如何在查询购买时加载PurchaseOrderDetails 模型?
  2. 这是获取所有购买conext的最佳方式吗?
  3. 提前致谢

2 个答案:

答案 0 :(得分:9)

我的抱歉因为我不经常在Stack Overflow中发表评论所以我不确定这是否应该发布。

仅供参考,sqlalchemy.orm.subqueryload_all已被弃用(自版本0.9.0起)。

他们现在希望您使用方法链。

session.query(MyClass).options(
    subqueryload("someattribute").subqueryload("anotherattribute")
)

答案 1 :(得分:5)

将查询的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上的文档在列出的示例中非常明确。