对于以下查询:

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总是试图优化exists()查询。如果mysql,则使用LIMIT 1

SELECT 1 FROM people LIMIT 1

正如Daniel在评论中指出的,您可以通过查看connection.queries,来探索Django所做的底层查询:
from django.db import connection

res = People.objects.all().exists()
print connection.queries

有关详细信息,请访问How can I see the raw SQL queries Django is running?
仅供参考,has_results()类中的django.db.models.sql.Query方法负责构造exists()查询。

关于python - django如何实现存在检查,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25851866/

10-14 14:57
查看更多