14

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!

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64

2 Answers2

17

Q(pk__in=[]) should do the trick.

Saeed
  • 3,294
  • 5
  • 35
  • 52
akaariai
  • 714
  • 3
  • 6
  • 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