gpt4 book ai didi

python - django如何实现存在性检查

转载 作者:行者123 更新时间:2023-11-29 01:57:05 26 4
gpt4 key购买 nike

对于以下查询:

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?

仅供引用,django.db.models.sql.Query 中的has_results() 方法类负责构造 exists() 查询。

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com