何时评估Django QuerySet? [英] When is a Django QuerySet evaluated?

查看:72
本文介绍了何时评估Django QuerySet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过Django queryset很懒。但这是否意味着懒惰,因为我可以在一条语句上链接多个操作,或者由于查询被延迟到需要结果时才懒惰。例如,以下模拟代码是否执行两个或三个SQL查询?

I've read django queryset are lazy. But does that mean lazy in that I can chain multiple operations on one statement or lazy in that the query is delayed to when the results are needed. For example, Does the following mock code execute two or three SQL queries?

query = Books.objects.filter(pk=book_id)
if query.exists():
  result = query.get()
else:
# ...


推荐答案

实际上是懒惰的,因为查询被延迟到需要结果的时候。在您的代码段中,第一行创建了一个未评估的查询集,并且没有到达数据库。第二行肯定会触发SQL查询。第三行-如果执行,将第二次访问数据库。

It's actually "lazy in that the query is delayed to when the results are needed". In your code snippet, the first line creates an unevaluated queryset and doesn't hit the DB. The second line do trigger a SQL query for sure. The third line - if executed - will hit the DB a second time.

如果设置 settings.DEBUG,您可以自己检查FWIW。 = True

>>> from django.contrib.auth.models import *
>>> from django.db import connection
>>> connection.queries
[]
>>> query = User.objects.filter(pk=1)
>>> connection.queries
[]
>>> query.exists()
True
>>> connection.queries
[{u'time': u'0.000', u'sql': u'SELECT (1) AS `a` FROM `auth_user` WHERE `auth_user`.`id` = 1  LIMIT 1'}]
>>> query.get()
<User: root>
>>> connection.queries
[{u'time': u'0.000', u'sql': u'SELECT (1) AS `a` FROM `auth_user` WHERE `auth_user`.`id` = 1  LIMIT 1'}, 
 {u'time': u'0.000', u'sql': u'SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`date_joined` FROM `auth_user` WHERE `auth_user`.`id` = 1 '}]
>>> 

这篇关于何时评估Django QuerySet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆