Using django.db.connection.queries
I've got a Python/Django application which runs quite a lot of SQL statements. For debuggi开发者_运维问答ng purposes, I thought I should create a simple view for me which just lists all the SQL statements that have been run.
According to the documentation, this code should be enough to do that:
from django.db import connection
connection.queries
as long as DEBUG is True.
However, this is not giving me anything. DEBUG is most certainly set to True. In what context is this connection.queries stored? I'm mean, I should be able to execute one page which executes a lot of SQL statements, and then just switch over to the http://myserver/sql view I created and see those SQL statements there, right? Using the same browser session of course ...
I did check if db.reset_queries() was being run anywhere in the code, appears it's not.
Any ideas why connection.queries is always empty?
Ben is right that you only see queries from the current process. You can use it within the same view, or in the console, but not between views.
The best way to see what queries are executing in your views is to use the Django debug toolbar.
@Daniel Roseman its a good idea, but if you want to know sql queries out of the box:
install django-command-extensions and add it to installed apps. it will add many utils commands into your project, one of them:
- debugsqlshell: Outputs the SQL that gets executed as you work in the Python interactive shell.
example:
python manage.py debugsqlshell
In [1]:from django.contrib.auth.models import User
In [1]:User.objects.all()
Out[2]: SELECT "auth_user"."id",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."password",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."is_superuser",
"auth_user"."last_login",
"auth_user"."date_joined"
FROM "auth_user" LIMIT 21 [1.25ms]
I think these queries are stored in memory, and not shared between processes, so you will only have access to the queries made by the current process.
If I try the code that you pasted in a ./manage.py shell
session, I only see queries I've previously made in that shell session.
If I pass queries
from a view into a template context and show it in the template, I see just the queries made in that view. This is using the dev server, though.
I assume—but haven't tested—that if you use this in an environment where you have one process serving multiple requests, you would see more queries being saved each request.
from django.db import connections
x = connections['rating']
x.queries
So check another connections!
That is what fixed it for me; I used:
reduce(lambda n, name: n + connections[name].queries, connections, 0)
to get the query count.
精彩评论