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()
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()
Yes, because in this case str
uses __repr__
.
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.
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
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).
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.
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).