0

好的,我们有三个表: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)

有什么建议可以做得更好吗?

4

1 回答 1

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')]

艾伦

于 2013-05-25T06:39:25.543 回答