sql_queries does not include all the sql statements

11 views
Skip to first unread message

leopay

unread,
Apr 29, 2008, 3:07:54 AM4/29/08
to Django users
I use django.core.context_processors.debug to see the sql_queries in
template.
The raw sql of query

Entry.objects.all()[0,1]

does not in the sql_queries,but if I change the query like this

Entry.objects.all()[0]

and then the sql is in the sql_queries. why?

Amit Ramon

unread,
Apr 29, 2008, 4:11:41 AM4/29/08
to django...@googlegroups.com
* leopay <leo...@gmail.com> [2008-04-29 00:07 -0700]:
I didn't understand the problem completely, but the syntax of your first example is incorrect. You probably meant ...[0:1] - this is the syntax for slicing.

If this doesn't help, try to provide more details.

--- Amit

leopay

unread,
Apr 29, 2008, 4:31:08 AM4/29/08
to django...@googlegroups.com
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

Simon Willison

unread,
Apr 29, 2008, 6:00:38 AM4/29/08
to Django users
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
Reply all
Reply to author
Forward
0 new messages