I wonder which is the correct way to construct a Q(...)
object which matches no object in the queryset. It seems that both Q()
and ~Q()
match all objects!
Asked
Active
Viewed 2,243 times
14

Tomasz Jakub Rup
- 10,502
- 7
- 48
- 49

Emanuele Paolini
- 9,912
- 3
- 38
- 64
-
Which is the query you want to do? – trinchet Apr 27 '15 at 16:55
-
I want to find a q such that M.objects.filter(q) is the same as M.objects.none() – Emanuele Paolini Apr 27 '15 at 17:57
-
Why not using EmptyQuerySet? – trinchet Apr 27 '15 at 18:05
-
Because the filter q is constructed once and used many times. I don't want to put an if...else each time it is used. – Emanuele Paolini Apr 27 '15 at 18:17
2 Answers
17
-
It's nice to note that the optimizer will correctly simplify complex expressions. Queries for `( Q(pk__in=[]) & Q(foo="bar") ) | Q(hello="world")` will simplify the condition to `WHERE "hello" = world`. It also works with tilde `~` negations. `Q(pk=None)` does not get optimized the same way (presumably because `pk` can be overridden). – Jonathan Richards Jan 15 '20 at 03:11
7
Q(pk=None)
works fine.
Q(pk__in=[])
works fine as well and doesn't hit the database.

Sven R. Kunze
- 1,909
- 2
- 13
- 17