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.
Q(pk__isnull=True) is better, because PRIMARY KEY cannot contain NULL values. There is possibility of that some instance could have id=0.
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)'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With