如何在Django中获取COUNT个查询 [英] How to get COUNT query in django

查看:33
本文介绍了如何在Django中获取COUNT个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在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 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 并且您无法从其他进程访问它们,不能在视图之间共享时起作用.

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

最好的选择是使用 Django调试工具栏.

这篇关于如何在Django中获取COUNT个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆