简体   繁体   English

如何在 Django 中获取 COUNT 查询

[英]How to get COUNT query in django

To get a query in django I can do:要在 Django 中进行查询,我可以执行以下操作:

>>> 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?但是,如何在执行 COUNT 时获得它构建的查询?

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

From docs:文档:

count()数数()

Returns an integer representing the number of objects in the database matching the QuerySet.返回一个整数,表示数据库中与 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.但是,您可以使用django.db.connection.queries来查看和访问当前进程所做的查询。

>>> 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.请注意,这仅在DEBUG=True并且您无法从另一个进程访问它们,您无法在视图之间共享。

The best option would be to use the Django debug toolbar .最好的选择是使用Django 调试工具栏

CaptureQueriesContext will grab the query for you after it's run, and I think works without DEBUG : CaptureQueriesContext将在运行后为您获取查询,我认为无需DEBUG

from django.test.utils import CaptureQueriesContext
with CaptureQueriesContext(conn) as queries:
    value = User.objects.count()
    print(queries.captured_queries[0]['sql'])

如果打开了 DEBUG,您始终可以从连接对象中获取 Django 执行的查询,如文档中所述

如果您只想查看查询,只需安装 Django 调试工具栏: https : //github.com/django-debug-toolbar/django-debug-toolbar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM