Reputation: 1022
I have a situation like this:
ids = [None, None, None]
foo = Foo.objects.filter(common=True).exclude(id__in=ids)
This seems to exclude all always.
Why is id
of id__in
threated as None
in this case? pk__in
didn't work either. I expect it to not exclude anything as all objects have valid id's.
foo = Foo.objects.filter(common=True)
Returns all objects like expected.
Upvotes: 6
Views: 3012
Reputation: 308829
Your queryset will generate SQL similar to select * from foo where NOT (id in (NULL));
In SQL both x in (NULL)
and NOT (x in (NULL))
evaluate to null
, so the query returns no rows. See this question for more info.
The solution, as @wim pointed out in the comments, is to filter out the None
values from the list:
foo = Foo.objects.filter(common=True).exclude(id__in=[x for x in ids if x is not None])
Upvotes: 7