SQLAlchemy:一个"全包"在_

时间:2015-03-30 08:45:10

标签: sqlalchemy

在通常的客户中 - >订购示例模式,如果我们想要将订单的所有客户订单设置为12或13,我们会告诉SQLAlchemy ......

for customer in db.query(Customer)\
        .join(Order, Customer.id = Order.cst_id)\
        .filter(Order.order_category_id.in_([12,13]):
    # do something with customer
    ...

但是,如果我们希望得到Customer的所有Order s,其中包含12 13 order_category_id s,该怎么办?在SQL中,我将其写为:

select * 
from Customer
where 
   exists (select 1 from Order 
    where Customer.id = Order.cst_id and Order.order_category_id = 12)
   and exists (select 1 from Order 
    where Customer.id = Order.cst_id and Order.order_category_id = 13)

如何触发SQLAlchemy生成此类查询?即一个返回与12和13 category_ids的订单行相关联的客户实体?

1 个答案:

答案 0 :(得分:2)

这样的事情:

subq1 = (
    Customer.query
    .join(Order, Customer.id = Order.cst_id)
    .filter(Order.order_category_id == 12)
).subquery()

final_query = (
    query(subq1)
    .join(Order, Customer.id = Order.cst_id)
    .filter(Order.order_category_id == 13)
)

我没有对此进行测试,但我认为它应该可行。