Python django如何实现存在性检查

Python django如何实现存在性检查,python,mysql,django,django-models,django-orm,Python,Mysql,Django,Django Models,Django Orm,对于以下查询: res = People.objects.all().exists() django使用mysql后端到底在做什么?是否有以下情况: cursor.execute('SELECT * FROM people') results = cursor.fetchall() if results: res = True else: res = False 或者,它是否使用了更为升级的功能,例如: cursor.execute('SELECT 1 FROM people

对于以下查询:

res = People.objects.all().exists()
django使用mysql后端到底在做什么?是否有以下情况:

cursor.execute('SELECT * FROM people')
results = cursor.fetchall()
if results:
    res = True
else:
    res = False
或者,它是否使用了更为升级的功能,例如:

cursor.execute('SELECT 1 FROM people')
if cursor.fetchone():
    res = True
else:
    res = False

Django总是尝试优化查询。在
mysql
的情况下,它使用
LIMIT 1

SELECT 1 FROM people LIMIT 1
正如Daniel在评论中指出的,您可以通过查看
连接来探索Django提出的底层查询

from django.db import connection

res = People.objects.all().exists()
print connection.queries
有关更多信息,请参阅


仅供参考,
has\u results()
类中的方法负责构造
exists()
查询。

为什么不检查查询本身?可以在shell中使用
connection.querys
,也可以在应用程序中使用Django调试工具栏。@DanielRoseman您能告诉我如何在视图代码中使用
connection.querys
?@peterdegloper
exists()。query
不起作用
exists()
返回一个布尔值。