exists() in django

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.
exists() is useful for searches relating to both object membership in a QuerySet and to the existence of any objects in a 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 iterating through 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 efficiency gains).
Additionally, if a some_queryset has not yet been evaluated, but you know that it will be at some point, then using some_queryset.exists() will do more overall work (one query for the existence check plus an extra one to later retrieve the results) than simply using bool(some_queryset), which retrieves the results and then checks if any were returned.



============


Example:

f you use get(), e.g. scorm.objects.get(pk=someid), and the object does not exists, a DoesNotExist exception is raised:
from django.core.exceptions import ObjectDoesNotExist
try:
    sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
    print ...



Update: it's also possible exists():
if scorm.objects.filter(Header__id=qp.id).exists():
    ....
Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.


=============

No comments:

Post a Comment