2

Will the queryset be evaluated i.e will django make database hits if i just stringify the queryset ?

i.e Will the below statement make database hits?

str(Model.objects.all())

The documentation doesn't cleary mentions about str()

asad_hussain
  • 1,959
  • 1
  • 17
  • 27

3 Answers3

1

Short answer

Yes, because in this case str uses __repr__.

Reasoning:

According to this excellent SO answer on repr vs str in python:

if __repr__ is defined, and __str__ is not, the object will behave as though __str__=__repr__

Looking at the django code we see that __repr__ is defined and __str__ is not, so we can reason that the docs on repr cover str as well.

Try it

It's pretty easy to test this sort of thing out yourself:

>>> from django.db import connection
>>> len(connection.queries)
0
>>> str(User.objects.all())
"<QuerySet [<User: test>, ...]>"
>>> len(connection.queries)
1

Comment on some other answers

Database is not directly hit by calling all(), which is the beauty of the lazy queryset evaluation. A DB query is not triggered until the elements of the response are required (as stated in the documentation pointed to by the OP).

RishiG
  • 2,790
  • 1
  • 14
  • 27
0

For stringfy, i think there won't be any Database hit. only for Model.objects.all() it will hit the database. Once the result came, It will stringfy the queryset without database hit.

str() is just type conversion functions to strings.

Sakthi Panneerselvam
  • 1,337
  • 1
  • 14
  • 25
0

Your code will only hit the DB once. Calling Model.objects.all() will include an SQL conversion that gets sent to the DB. Once received by your application, the str() call only calls the __str__ method inside a Model. If not defined, I think it will return a default syntax involving the primary key(which I can't remember off the top of my head since I always define __str__ for readability and testing purposes).

zero
  • 1,605
  • 3
  • 15
  • 24