On Apr 29, 9:31 am, leopay <
leo...@gmail.com> wrote:
> oh,sorry ,I made a mistake,it is Entry.objects.all()[0:1]
> I means when I write like this Entry.objects.all()[0:1],I cannot find the
> this raw sql like 'select col_name from entry_table limit 1' in
> sql_queries,but if I write like this Entry.objects.all()[0],I could the sql
> in sql_queries when use django.core.context_processors.debug
This is due to the way QuerySets are lazily evaluated. A QuerySet will
not result in the execution of SQL until the last possible moment. You
can experiment with this in ./manage.py shell:
>>> from django.db import connection
>>> a = models.Question.objects.all()
>>> connection.queries
[]
>>> print a
[<Question: What is your name?>]
>>> connection.queries
[{'sql': u'SELECT `blah_question`.`id`,`blah_question`.`question` FROM
`blah_question`',
'time': '0.001'}]
In the above case, the SQL was not executed until the queryset was
printed (which requires the database results).
In your case though:
>>> from django.db import connection
>>> a = models.Question.objects.all()[0]
>>> connection.queries
[{'sql': u'SELECT `blah_question`.`id`,`blah_question`.`question` FROM
`blah_question` LIMIT 1 ',
'time': '0.001'}]
Accessing [0] on the QuerySet forces it to be executed, so the SQL
query has to be run.
Using the slice [0:1] does NOT cause the query to be run straight
away; instead, it adds limit and potentially offset clauses to the SQL
statement that is being prepared by the QuerySet.
Hope that clears things up,
Simon