6

Now I use just Q(id=0), and that depends on DB. Or maybe Q(pk__isnull=True) is better? It is useful for concatenation Q objects with using of | operator.

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
Pycz
  • 366
  • 3
  • 12

3 Answers3

3

Q(pk__isnull=True) is better, because PRIMARY KEY cannot contain NULL values. There is possibility of that some instance could have id=0.

f43d65
  • 2,264
  • 11
  • 15
1

Actually, there is a special method in Django QuerySet. Model.objects.none() always returns empty queryset and is more clear for understanding.

Pycz
  • 366
  • 3
  • 12
1

The query optimizer handles Q(pk__in=[]) better than Q(pk__isnull=True). For example:

Model.objects.filter(Q(pk__in=[]) # doesn't hit the DB
Model.objects.none() # doesn't hit the db
Model.objects.filter(Q(pk__isnull=True)) # hits the DB

If even works with complex queries and tilde negation:

Model.objects.filter( (Q(pk__in=[]) & Q(foo="bar")) | Q(hello="world") )
# simplifies condition to 'WHERE "hello" = world'

Model.objects.filter( ~(~Q(pk__in=[]) & Q(foo="bar")) | Q(hello="world") )
# simplifies condition to 'WHERE (NOT ("foo" = bar) OR "hello" = world)'

Jonathan Richards
  • 1,414
  • 1
  • 16
  • 20