1

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

So which one is most preferable way & why ?
I extended answer - please check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.