我有这样的情况:
ids = [None, None, None]
foo = Foo.objects.filter(common=True).exclude(id__in=ids)
这似乎总是排除所有。
在这种情况下,为什么 id__in 的 id 被威胁为 None? pk__in 也没有用。我希望它不会排除任何东西,因为所有对象都有有效的 ID。
foo = Foo.objects.filter(common=True)
按预期返回所有对象。
请您参考如下方法:
您的查询集将生成类似于 select * from foo where NOT (id in (NULL));
在 SQL 中,x in (NULL) 和 NOT (x in (NULL)) 的计算结果都是 null,因此查询返回 no行。参见 this question了解更多信息。
正如@wim 在评论中指出的那样,解决方案是从列表中过滤掉 None 值:
foo = Foo.objects.filter(common=True).exclude(id__in=[x for x in ids if x is not None])
