[Fixed]-Using django.db.connection.queries


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.

python manage.py debugsqlshell

In [1]:from django.contrib.auth.models import User
In [1]:User.objects.all()

Out[2]: SELECT "auth_user"."id",
    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']

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.


Leave a comment