Django ORM apply .filter() to an existing queryset
I'm a bit confused about requests into database to be executed in this code snippet
>>> from core.models import People
>>> p = People.objects.all()
>>> p.filter(age__gt=10)
It's clear that passing objects.all()
into ORM will lead to one request like SELECT *
However, if I apply .filter()
method to an existing queryset, will it lead to second request to database?
Or ORM will look through the existing queryset?
Thank you
Solution 1:
However, if I apply
.filter()
method to an existing queryset, will it lead to second request to database?
constructing querysets will not make a database query. Indeed, here p = People.objects.all()
will not make a query.
Querysets will make a query if you "consume" the queryset. You consume the queryset if you iterate over it, call len(…)
, str(…)
en repr(…)
over it, etc.
This thus means that if you print p.filter(age__gt=10)
, it will only make a query with SELECT people.* FROM people WHERE age > 10
. If you later for example print p
, it will make a second query SELECT people.* FROM people
.
Querysets also cache the result when they are consumed. So if you iterate a second time on the same QuerySet
, it will reuse the result of the previous query.