好的,我们有三个表:Order、Product 和 OrderProduct。我想查找Orders有哪些产品,我写了如下函数:
def get_orders_with_products(products):
if len(products) < 1:
raise Exception("at least one product expected")
query = get_order_set_query(products[0])
if len(procducts > 1):
for product in products[1:]:
query = query & get_order_set_query(product)
return Order.objects.filter(query)
def get_order_set_query(product):
product_orders = OrderProduct.objects \
.values_list('order_id', flat=True)\
.filter(product=product)
return Q(id__in=set(product_orders))
此代码将导致如下所示的 sql 查询:
select * from Orders
where id in [1, 2, 3]
and id in [2, 3, 4]
有什么办法可以让 Django 的 ORM 写出下面的查询?
select * from Orders
where id in (select order_id from OrderProduct where product_id = 1)
and id in (select order_id from OrderProduct where product_id = 2)
有什么建议可以做得更好吗?