Django objects.all () vs objects.filter ()

Queryset.objects.all() return all objects as well

Queryset.objects.filter() return all objects.

I have two queries that use Queryset.objects.filter(), and I want to use it to return all objects.

Question : Do the same Queryset.objects.all()and Queryset.objects.filter() the performance ?

+4
source share
2 answers

From Django source code below, it is almost the same. Both methods are called a method _chain. With the help of filteryou create an object Qwithout any children, but there is not much overhead.

Use allis preferable, however, since it eliminates the execution of unnecessary code.

def all(self):
    """
    Return a new QuerySet that is a copy of the current one. This allows a
    QuerySet to proxy for a model manager in some cases.
    """
    return self._chain()

def filter(self, *args, **kwargs):
    """
    Return a new QuerySet instance with the args ANDed to the existing
    set.
    """
    return self._filter_or_exclude(False, *args, **kwargs)

def _filter_or_exclude(self, negate, *args, **kwargs):
    if args or kwargs:
        assert self.query.can_filter(), \
            "Cannot filter a query once a slice has been taken."

    clone = self._chain()
    if negate:
        clone.query.add_q(~Q(*args, **kwargs))
    else:
        clone.query.add_q(Q(*args, **kwargs))
    return clone
+3
source

, , - . , , , .

, , all() , , .

+8

Source: https://habr.com/ru/post/1695701/


All Articles