I wonder which is the correct way to construct a Q(...)
object which matches no object in the queryset. It seems that both Q()
and ~Q()
match all objects!
how to construct django Q object matching none
Which is the query you want to do? –
Favien
I want to find a q such that M.objects.filter(q) is the same as M.objects.none() –
Bijouterie
Why not using EmptyQuerySet? –
Favien
Because the filter q is constructed once and used many times. I don't want to put an if...else each time it is used. –
Bijouterie
Q(pk__in=[])
should do the trick.
It's nice to note that the optimizer will correctly simplify complex expressions. Queries for
( Q(pk__in=[]) & Q(foo="bar") ) | Q(hello="world")
will simplify the condition to WHERE "hello" = world
. It also works with tilde ~
negations. Q(pk=None)
does not get optimized the same way (presumably because pk
can be overridden). –
Irizarry Q(pk=None)
works fine.
Q(pk__in=[])
works fine as well and doesn't hit the database.
© 2022 - 2024 — McMap. All rights reserved.