Moon
Moon

Reputation: 4160

What is difference between objects.all().annotate and objects.annotate?

Currently I am practicing for annotate and have some confusion regarding below code.

>>> b = Book.objects.all().annotate(upper_name = Upper('name'))
>>> b[0].name
'Book1'
>>> b[0].upper_name
'BOOK1'
>>> ba = Book.objects.annotate(upper_name = Upper('name'))
>>> ba[0]
<Book: Book1>
>>> ba[0].name
'Book1'
>>> ba[0].upper_name
'BOOK1'

I am getting same output when not using all() so what is difference between using Book.objects.all() and 'Book.objects.annotate()'.

How doing annotate() on Book objects without all() provide all Book objects.

I have read Django documentation but not able to find any answer.

Thanks.

Upvotes: 1

Views: 166

Answers (1)

Charnel
Charnel

Reputation: 4432

There is no difference because all actually calls get_queryset on model manager to return queryset. You can check the implementation of BaseManager to see this.

Using all() is preferable because it's guaranteed to return a QuerySet instance that you can further iterate/filter/etc, where using manager returns Manager instance that you can filter/annotate/whatever but can't use in same way as queryset.

Example:

for book in Book.objects:
    # this will fail

for book in Book.objects.all():
    # this will work

Upvotes: 1

Related Questions