如何在Django中获取COUNT个查询 [英] How to get COUNT query in django
问题描述
要在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`
但是,当执行COUNT时,我如何获取它生成的查询?
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'
推荐答案
来自 count()
返回一个整数,代表与查询集匹配的数据库中的对象数. Returns an integer representing the number of objects in the database matching the QuerySet. 因此,您不能. However, you can make use of 请注意,这仅在 Note that, this works only when 最好的选择是使用 Django调试工具栏. 这篇关于如何在Django中获取COUNT个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!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
DEBUG = True
并且您无法从其他进程访问它们,不能在视图之间共享时起作用.DEBUG=True
and you can't access them from another process, you can't share between views.