Django Q过滤器否定不会产生预期的查询

时间:2015-02-27 15:19:11

标签: django django-queryset django-q

简化设置

class System(models.Model):
    fields...
    vulnerabilities = models.ManyToManyField('Vulnerability', through='SystemVulnerability')

class Vulnerablity(models.Model):
    name = ...
    risk = CharField(choices=['H','M','L','I'])
    ...

class SystemVulnerability(models.Model):
    vulnerability = ForeignKey
    system = ForeignKey
    fields...

sv_list = [199026, 199036, 199046, 199048, ....]
other_filter = Q(... lots of stuff...) #not including this for brevity

System.objects.filter(other_filter & Q(systemvulnerability__in=sv_list)).query.__str__()
u'SELECT "system"."id", "system"."ip", "system"."org_id", "system"."dnsname", "system"."ipownercode", "system"."securityplan" 
    FROM "system" 
    INNER JOIN "systemvulnerability" ON ( "system"."id" = "systemvulnerability"."system_id" ) 
    WHERE "systemvulnerability"."id" IN (199026, 199036, 199046, 199048, ....)'

看起来不错。如果我们否定它会怎么样?

System.objects.filter(other_filter & ~Q(systemvulnerability__in=sv_list)).query.__str__()
u'SELECT "system"."id", "system"."ip", "system"."org_id", "system"."dnsname", "system"."ipownercode", "system"."securityplan" 
    FROM "system" 
    WHERE NOT ("system"."id" IN (SELECT U1."system_id" FROM "systemvulnerability" U1 WHERE U1."id" IN (199026, 199036, 199046, 199048, ....)))'

什么? 我希望得到的查询是:

u'SELECT "system"."id", "system"."ip", "system"."org_id", "system"."dnsname", "system"."ipownercode", "system"."securityplan" 
    FROM "system" 
    INNER JOIN "systemvulnerability" ON ( "system"."id" = "systemvulnerability"."system_id" ) 
    WHERE "systemvulnerability"."id" NOT IN (199026, 199036, 199046, 199048, ....)'

如何修改我的语句,以便生成的查询更符合我的期望?

Example data

System:
s1
s2
s3

Vulnerability:
v1
v2
v3

SystemVulnerability:
sv1 = s1, v1
sv2 = s1, v2
sv3 = s2, v2
sv4 = s3, v2
sv5 = s3, v3

System.filter(Q(systemvulnerability__in=[sv1, sv4]))
Get back s1, s3: Good!

System.filter(~Q(systemvulnerability__in=[sv1, sv2]))
Get back: s2, s3: Good!

System.filter(~Q(systemvulnerability__in=[sv1, sv4, sv5]))
Get back s2: Bad!
But I wanted s1, s2

显然我可以基于SystemVulnerability进行查询,但我的过滤器实际上要比这复杂得多,所以我想基于System保留它。

我想System.objects.filter(pk__in=SystemVulnerability.filter(~Q(systemvulnerability__in=sv_list)).values_list('system')) 可以工作,但SQL中生成的IN子句相当大而且速度慢,特别是当我的数据增长时。

编辑:我去尝试用前一行的IN子句来做。它可以工作,但最终否定了我的很多其他过滤器。我真的需要~Q()才能正常地处理关系!

1 个答案:

答案 0 :(得分:0)

这不是一个真正的答案,但几天后我设法考虑如何在不排除的情况下重写这一点。我的SQL开发对我的所作所为感到痛苦,但它在django中的效果要好于做.extra(where=[])这就是我开始做的事情。这会让我以这种方式重写太多的查询。