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