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

3

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.

Tryst answered 1/7, 2015 at 12:13 Comment(0)
T
1

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

Tryst answered 6/12, 2018 at 14:43 Comment(0)
J
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.

Jasen answered 1/7, 2015 at 12:48 Comment(0)
T
1

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

Tryst answered 6/12, 2018 at 14:43 Comment(0)
F
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)'

Flagg answered 16/1, 2020 at 3:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.