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.
The right way to make Q object, which filter all entries in Django QuerySet?
Asked Answered
Actually, there is a special method in Django QuerySet.
Model.objects.none()
always returns empty queryset and is more clear for understanding.
Q(pk__isnull=True)
is better, because PRIMARY KEY
cannot contain NULL
values. There is possibility of that some instance could have id=0
.
Actually, there is a special method in Django QuerySet.
Model.objects.none()
always returns empty queryset and is more clear for understanding.
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)'
© 2022 - 2024 — McMap. All rights reserved.