How to get COUNT request in django

To get the request 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 can I get the query that it creates when executing COUNT?

 >>> User.objects.all().count().query Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'int' object has no attribute 'query' 
+5
source share
3 answers

From docs:

counter()

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

So you cannot.

However, you can use django.db.connection.queries to view and access requests that are running by the current process.

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

Please note that this only works when DEBUG=True and you cannot access them from another process, you cannot share between views.

A better option would be to use the Django debug toolbar .

+4
source

If DEBUG is enabled, you can always get requests made by Django from the connection object, as described in the documentation .

0
source

If you just want to see the query, just install the Debug Django toolbar: https://github.com/django-debug-toolbar/django-debug-toolbar

0
source

Source: https://habr.com/ru/post/1213882/


All Articles