Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between if and if exists()?

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?

like image 276
BSG Avatar asked Dec 25 '22 12:12

BSG


1 Answers

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.

like image 120
André Laszlo Avatar answered Dec 28 '22 01:12

André Laszlo