查询集何时使用_result_cache,而不是访问数据库?

hoc*_*836 1 django orm django-queryset

我对查询集使用它_result_cache或它直接命中数据库的时间感到困惑.

例如(在python shell中):

user = User.objects.all()  # User is one of my models   
print(user)  # show data in database (hitting the database)   
print(user._result_cache)  # output is None   
len(user)  # output is a nonzero number  
print(user._result_cache)  # this time, output is not None   
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:

  1. 为什么_result_cache就是None命中数据库后?
  2. 查询集是否被评估意味着_result_cache不是None
  3. 查询集何时使用它_result_cache,而不是命中数据库?

knb*_*nbk 6

self._result_cache只要评估完整的查询集,查询集就会缓存其数据.这包括遍历查询集,调用bool(),len()list(),或酸洗查询集.

print()函数间接调用repr()查询集.repr()将评估查询集以将数据包含在字符串表示中,但它不会评估完整的查询集.相反,它将获得查询集的一部分并在表示中使用它.当你想要的只是一个简单的字符串表示时,这可以防止大量查询 由于仅评估切片,因此不会缓存结果.

填充缓存时,每个不创建新查询集对象的方法都将使用缓存而不是创建新查询.在您的特定示例中,如果切换print()len()语句,您的查询集将只访问数据库一次:

user = User.objects.all()
len(user)  # complete queryset is evaluated
print(user._result_cache)  # cache is filled
print(user)  # slicing an evaluated queryset will not hit the database
print(user._result_cache)
Run Code Online (Sandbox Code Playgroud)