exists()
¶
exists
()
¶
Returns True
if the QuerySet
contains any results, and False
if not. This tries to perform the query in the simplest and fastest waypossible, but it does execute nearly the same query as a normalQuerySet
query.
exists()
is useful for searches relating to bothobject membership in a QuerySet
and to the existence of any objects ina QuerySet
, particularly in the context of a large QuerySet
.
The most efficient method of finding whether a model with a unique field(e.g. primary_key
) is a member of a QuerySet
is:
entry = Entry.objects.get(pk=123)
if some_queryset.filter(pk=entry.pk).exists():
print("Entry contained in queryset")
Which will be faster than the following which requires evaluating and iteratingthrough the entire queryset:
if entry in some_queryset:
print("Entry contained in QuerySet")
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")
… but not by a large degree (hence needing a large queryset for efficiencygains).
Additionally, if a some_queryset
has not yet been evaluated, but you knowthat it will be at some point, then using some_queryset.exists()
will domore overall work (one query for the existence check plus an extra one to laterretrieve the results) than simply using bool(some_queryset)
, whichretrieves the results and then checks if any were returned.