好的,我们有三个表: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)
有什么建议可以做得更好吗?
答案 0 :(得分:0)
是
from django.db.models import Q
queryset = Order.objects.filter(Q(order_id = [1, 2, 3]) & Q(order_id = [2, 3, 4]))
您可以使用
之类的内容替换列表[id[0] for id in OrderProduct.objects.filter(product_id = 1).values_list('id')]
艾伦