how to construct django Q object matching none
Asked Answered
B

2

16

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!

Bijouterie answered 27/4, 2015 at 15:51 Comment(4)
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
R
18

Q(pk__in=[]) should do the trick.

Rodriquez answered 28/4, 2015 at 7:57 Comment(1)
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
T
8

Q(pk=None) works fine.

Q(pk__in=[]) works fine as well and doesn't hit the database.

Thessalonian answered 20/6, 2018 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.