我试图从django查询集中排除在另一个查询集中具有外键的所有对象。但是,我没有成功使用exclude()
。请帮忙。
这是python shell的一个片段:
>>> shipped = shipment_detail.objects.all()
>>> shipped
[<shipment_detail: 4>]
>>> fo = fill_order.objects.exclude(product_order__in=shipped)
>>> fo
[<fill_order: 2>]
>>> for x in shipped:
... x.product_order.id
...
1
>>> fo
[<fill_order: 2>]
>>> for x in fo:
... x.product_order.id
...
1
我在debian wheezy上使用django 1.7,python 2.7.7,postgresql 9.3。
UPDATE :意识到我可以看到sql django正在使用。这里是。显然不是我想要实现的目标。看起来我需要明确地告诉django我的意思是引用FK id而不是记录id。
SELECT "box_inv_fill_order"."id", "box_inv_fill_order"."product_order_id",
"box_ inv_fill_order" ."date"
FROM "box_inv_fill_order"
WHERE NOT ("box_inv_fill_order"."product_order_id"
IN (SELECT "box_inv_shipment_detail"."id" FROM "box_inv_shipment_detail"))
答案 0 :(得分:2)
fo = fill_order.objects.exclude(product_order__in=shipped)
产地:
SELECT "box_inv_fill_order"."id", "box_inv_fill_order"."product_order_id",
"box_ inv_fill_order" ."date"
FROM "box_inv_fill_order"
WHERE NOT ("box_inv_fill_order"."product_order_id"
IN (SELECT "box_inv_shipment_detail"."id" FROM "box_inv_shipment_detail"))
将product_order_id
与shipment_detail_id
进行比较。 不我的意图!
<强>解决方案强>:
使用.filter(...__in=[r.product_order for r in shipped])
的@alecxe建议,创建一个嵌套的sql SELECT
作为IN
参数。
SELECT "box_inv_fill_order"."id", "box_inv_fill_order"."product_order_id", "box_inv_fill_order"."date"
FROM "box_inv_fill_order"
WHERE NOT ("box_inv_fill_order"."product_order_id"
IN (4))