Many times, one needs to check if there is at least one element inside a QuerySet
. Mostly, I use exists
:
if queryset.exists():
...
However, I've seen colleagues using python's any
function:
if any(queryset):
...
Is using python's any
function unoptimal?
My intuition tells me that this is a similar dilemma to one between using count
and len
: any
will iterate through the QuerySet
and, therefore, will need to evaluate it. In a case where we will use the QuerySet
items, this doesn't create any slowdowns. However, if we need just to check if any pieces of data that satisfy a query exist, this might load data that we do not need.
CodePudding user response:
Is using python's any function unoptimal?
The most Pythonic way would be:
if queryset:
# …
Indeed, a QuerySet
has truthiness True
if it contains at least one item, and False
otherwise.
In case you later want to enumerate over the queryset (with a for
loop for example), it will load the items in the cache if you check its truthiness, so for example:
if queryset:
for item in queryset:
# …
will only make one query to the database: one that will fetch all items when you check the if queryset
, and then later you can reuse that cache without making a second query.
In case you do not consume the queryset later in the process, then you can work with a .exists()
[Django-doc]: this will not load records in memory, but only make a query to check if at least one such record exists, this is thus less expensive in terms of bandwidth between the application and the database. If you however have to consume the queryset later, using .exists()
is not a good idea, since then we make two queries.
Using any(queryset)
however is non-sensical: you can check if a queryset contains elements by its truthiness, so using any()
will usually only make that check slightly less efficient.