Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get COUNT query in django

To get a query in django I can do:

>>> print User.objects.all().query
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`

However, how would I get the query it builds when doing a COUNT?

>>> User.objects.all().count().query
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'int' object has no attribute 'query'
like image 650
David542 Avatar asked Feb 21 '15 23:02

David542


2 Answers

From docs:

count()

Returns an integer representing the number of objects in the database matching the QuerySet.

Thus, you can't.

However, you can make use of django.db.connection.queries in order to see and access the queries that are made by the current process.

>>> from django.db import connection
>>> User.objects.count()
>>> print connection.queries

Note that, this works only when DEBUG=True and you can't access them from another process, you can't share between views.

The best option would be to use the Django debug toolbar.

like image 178
Ozgur Vatansever Avatar answered Sep 27 '22 18:09

Ozgur Vatansever


CaptureQueriesContext will grab the query for you after it's run, and I think works without DEBUG:

from django.test.utils import CaptureQueriesContext
from django.db import connection

with CaptureQueriesContext(connection) as queries:
    value = User.objects.count()
    print(queries.captured_queries[0]['sql'])
like image 32
Jack Cushman Avatar answered Sep 27 '22 19:09

Jack Cushman