Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right way to make Q object, which filter all entries in Django QuerySet?

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.

like image 466
Pycz Avatar asked Sep 27 '22 11:09

Pycz


2 Answers

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

like image 186
f43d65 Avatar answered Nov 04 '22 20:11

f43d65


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)'

like image 27
Jonathan Richards Avatar answered Nov 04 '22 18:11

Jonathan Richards