我有这样的情况:
ids = [None, None, None]
foo = Foo.objects.filter(common=True).exclude(id__in=ids)
Run Code Online (Sandbox Code Playgroud)
这似乎总是排除一切。
为什么会像这种情况一样id受到id__in威胁?也没有用。我希望它不会排除任何内容,因为所有对象都有有效的 ID。Nonepk__in
foo = Foo.objects.filter(common=True)
Run Code Online (Sandbox Code Playgroud)
按预期返回所有对象。
您的查询集将生成类似于以下的 SQLselect * from foo where NOT (id in (NULL));
在 SQL 中, 和x in (NULL)的NOT (x in (NULL))计算结果均为null,因此查询不返回任何行。请参阅此问题以获取更多信息。
None正如 @wim 在评论中指出的,解决方案是从列表中过滤掉值:
foo = Foo.objects.filter(common=True).exclude(id__in=[x for x in ids if x is not None])
Run Code Online (Sandbox Code Playgroud)