如果未包含在另一列中,则过滤结果

时间:2013-11-23 18:50:59

标签: sql django django-queryset

使用Django的QuerySet API执行以下SQL命令是否有相同的方法?

select id, childid from mysite_nodetochild
where childid NOT IN (Select "Nodeid" from mysite_nodetochild)

如果可能的话,我宁愿不使用原始的SQL,但是我无法使用Django的Queryset获得干净的工作版本。

1 个答案:

答案 0 :(得分:1)

尝试

nodetochild.objects.exclude(childid=nodetochild.objects.values_list('Nodeid', flat=True)).only('id', 'childid')

这应该或多或少地评估:

SELECT "mysite_nodetochild"."id", "mysite_nodetochild"."childid" FROM "mysite_nodetochild" WHERE NOT ("mysite_nodetochild"."childid" =  (SELECT U0."nodeid" FROM "mysite_nodetochild" U0))

或者,如果您需要IN条件:

nodetochild.objects.exclude(childid__in=nodetochild.objects.values_list('Nodeid', flat=True)).only('id', 'childid')

评估为:

SELECT "mysite_nodetochild"."id", "mysite_nodetochild"."childid" FROM "mysite_nodetochild" WHERE NOT ("mysite_nodetochild"."childid" IN  (SELECT U0."nodeid" FROM "mysite_nodetochild" U0))