- Returns Trueif theQuerySetcontains any results, andFalseif not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normalQuerySetquery.
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")
if entry in some_queryset:
   print("Entry contained in QuerySet")
if some_queryset.exists():
    print("There is at least one object in some_queryset")
if some_queryset:
    print("There is at least one object in some_queryset")
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():
    ....ReturnsTrueif the QuerySet contains any results, andFalseif 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