1👍
✅
QuerySets cache the value. That means that if you directly return self.queryset
, it will run the query once, and store the values in memory.
If you add .all()
, you make a copy of the QuerySet
without the cache, and you thus force making a new query.
This is why a ListView
by default has an implementation where it will return the queryset.all()
. Indeed, if we look at the source code [GitHub], we see:
def get_queryset(self): """ Return the list of items for this view. The return value must be an iterable and may be an instance of `QuerySet` in which case `QuerySet` specific behavior will be enabled. """ if self.queryset is not None: queryset = self.queryset if isinstance(queryset, QuerySet): queryset = queryset.all() elif self.model is not None: queryset = self.model._default_manager.all() else: raise ImproperlyConfigured( "%(cls)s is missing a QuerySet. Define " "%(cls)s.model, %(cls)s.queryset, or override " "%(cls)s.get_queryset()." % { 'cls': self.__class__.__name__ } ) ordering = self.get_ordering() if ordering: if isinstance(ordering, str): ordering = (ordering,) queryset = queryset.order_by(*ordering) return queryset
Source:stackexchange.com