Reputation: 6807
I've read django queryset are lazy. But does that mean lazy in that I can chain multiple operations on one statement or lazy in that the query is delayed to when the results are needed. For example, Does the following mock code execute two or three SQL queries?
query = Books.objects.filter(pk=book_id)
if query.exists():
result = query.get()
else:
# ...
Upvotes: 3
Views: 4595
Reputation: 77902
It's actually "lazy in that the query is delayed to when the results are needed". In your code snippet, the first line creates an unevaluated queryset and doesn't hit the DB. The second line do trigger a SQL query for sure. The third line - if executed - will hit the DB a second time.
You can check this by yourself FWIW, if you set settings.DEBUG=True
:
>>> from django.contrib.auth.models import *
>>> from django.db import connection
>>> connection.queries
[]
>>> query = User.objects.filter(pk=1)
>>> connection.queries
[]
>>> query.exists()
True
>>> connection.queries
[{u'time': u'0.000', u'sql': u'SELECT (1) AS `a` FROM `auth_user` WHERE `auth_user`.`id` = 1 LIMIT 1'}]
>>> query.get()
<User: root>
>>> connection.queries
[{u'time': u'0.000', u'sql': u'SELECT (1) AS `a` FROM `auth_user` WHERE `auth_user`.`id` = 1 LIMIT 1'},
{u'time': u'0.000', u'sql': u'SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`date_joined` FROM `auth_user` WHERE `auth_user`.`id` = 1 '}]
>>>
Upvotes: 10