M
M
Mat1lda2020-03-13 12:09:56
Django
Mat1lda, 2020-03-13 12:09:56

Does it make any difference where to put all()?

Question:
Is there a difference between and

Entry.objects.all().filter(pub_date__year=2006)
Entry.objects.filter(pub_date__year=2006).all()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2020-03-13
@fox_12

This question is revealed here .
.all() returns a copy of the current QuerySet for subsequent filtering or passing it to the model manager when you need to get exactly the QuerySet
. In addition, this QuerySet is cached, so if the data in the database has changed, you can get the results by calling .all() again for the expression.
.filter() also returns a QuerySet
So the entries mean:
Entry.objects.all().filter(pub_date__year=2006) - get a copy of the queryset, and return the filtered queryset
Entry.objects.filter(pub_date__year=2006).all() - get filtered queryset and return a copy of this queryset
and since .filter() already returns a filtered queryset, .all() can be omitted in this case

type(Entry)
class 'django.db.models.base.ModelBase'

type(Entry.objects)
class 'django.db.models.manager.Manager'

type(Entry.objects.all())
class 'django.db.models.query.QuerySet'

type(Entry.objects.all().(pub_date__year=2006))
class 'django.db.models.query.QuerySet'

synthetic example:
query = Entry.objects   # - в query менеджер некоей модели

for obj in query.all():  # вывели объекты
    print(obj)

... # тут к примеру проделали определенные манипуляции с некоторыми объектами

for obj in query.all():  # вывели обновленный список объектов
    print(obj)

D
Dr. Bacon, 2020-03-13
@bacon

He's not needed here at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question