python - 如何在 Django 中获取 COUNT 查询

标签 python mysql django

要在 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`

但是,我如何在执行 COUNT 时获取它构建的查询?

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

最佳答案

来自 docs:

count()

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

因此,您不能。

但是,您可以使用 django.db.connection.queries以便查看和访问当前进程进行的查询。

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

请注意,这仅在 DEBUG=True 时有效,并且您无法从另一个进程访问它们,也无法在 View 之间共享。

最好的选择是使用 Django debug toolbar .

关于python - 如何在 Django 中获取 COUNT 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28652584/

相关文章:

mysql - 在 MYSQL 中查询以获取来自另一个查询的两个值的结果

php - 在php中执行sql查询不起作用,但查询在phpmyadmin中起作用

django - 如何在 Django 博客中首先显示最近的帖子?

python - 从另一个列表的元素创建一个新列表,引用后者的元素

python - 通过公共(public) HTTP 自动将大文件检索到 Google Cloud Storage

python - 开发人员如何使用外部包管理应用程序大小?

django modelformset_factory - 管理表单数据丢失

python - 访问私有(private)类变量

php - 拥有一两个数据库更好?

python - Django:在原始 SQL 查询中使用命名参数