DJANGO:通过QuerySet排除()的FK字段查找

时间:2014-06-17 18:32:33

标签: python django postgresql orm

我试图从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"))

1 个答案:

答案 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_idshipment_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))