So the Django docs state the following:
And to find whether a queryset contains any items:
if some_queryset.exists(): print("There is at least one object in some_queryset")
Which will be faster than:
if some_queryset: print("There is at least one object in some_queryset")
Why is that though? What good reason is there? Often when evaluating a QuerySet
in a Boolean context, all a user cares about is whether there's at least one item which presumably is why exists
is faster. Why can't __bool__
on QuerySet
simply do the same amount of work as exists
?
Look at the source code, there seems to be a bit of work involved:
def __bool__(self):
self._fetch_all()
return bool(self._result_cache)
But no documentation providing context on why.
For me, simply calling if some_queryset:
is much cleaner and more Pythonic.