如何找到Django是否命中db

2024-05-07 16:06:56 发布

您现在位置:Python中文网/ 问答频道 /正文

据我所知,django查询集是惰性的,在评估之前不会命中db,在这种情况下,在将查询集分配给dict中的一个键之后,下面的行是否会导致每次命中db?请指教

abc = model1.objects.all()

content = {
    'entry' : abc, # Once assigned will the below lines hits db?
    'entry_count' : abc.count(), # will this hit db
    'entry1_count' : abc.filter(name__icontains = 'a').count(), # will this hit db
    'entry2_count' : abc.filter(name__icontains = 'b').count(), # will this hit db again?
    }

return render(request, template, content}

Tags: djangonamedbcount情况contentfilterthis
1条回答
网友
1楼 · 发布于 2024-05-07 16:06:56

除第一种情况外,它在所有情况下都会命中数据库

理论部分见文件:https://docs.djangoproject.com/en/2.2/topics/db/queries/

您可以使用django debug toolbar查看每个呈现页面的所有SQL查询

您还可以看到哪个查询是以编程方式执行的。例如,对于这一行:

abc.count()

您可以通过执行以下操作查看SQL查询:

print(abc.count().explain())

相关问题 更多 >