문제

Take any given queryset, qs = QS.objects.filter(active=True)

Is there i difference between:

if qs:

and

if qs.exists():

regarding load on the db, etc?

도움이 되었습니까?

해결책

Yes, there's a difference:

  • if qs will use the __nonzero__ method of the QuerySet object, which calls _fetch_all which will in turn actually execute a full query (that's how I interpret it anyway).
  • exists() does something more efficient, as noted by Ewan. That's why this method... exists.

So, in short, use exists() when you only need to check for existence since that's what it's for.

다른 팁

From the documentation of 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.

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.

However they then go on to show a few examples and conclude that if qs vs if qs.exists() needs a large queryset for efficiency gains.

A final caveat from the documentation:

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.

It produces the same result. From the help on https://docs.djangoproject.com/en/dev/ref/models/querysets/

exists()

Returns True if the QuerySet contains any results, and False if not.

bool()

Testing a QuerySet in a boolean context, ..., will cause the query to be executed. If there is at least one result, the QuerySet is True, otherwise False.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top