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

20👍

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.

9👍

@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]

3👍

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.

2👍

from django.db import connections
x = connections['rating']
x.queries

So check another connections!

0👍

That is what fixed it for me; I used:

reduce(lambda n, name: n + connections[name].queries, connections, 0)

to get the query count.

👤2ps

Leave a comment