Python 当您请求对象时,django是否会访问数据库';缓存查询中的属性?
我很难理解如何正确使用缓存框架。假设我有以下代码:Python 当您请求对象时,django是否会访问数据库';缓存查询中的属性?,python,django,database,caching,memcached,Python,Django,Database,Caching,Memcached,我很难理解如何正确使用缓存框架。假设我有以下代码: class Book(models.Model): title = models.CharField() author = models.ForeignKey(User) @classmethod: def get_all_books(cls): query = cache.get_or_set( 'all_books', cls
class Book(models.Model):
title = models.CharField()
author = models.ForeignKey(User)
@classmethod:
def get_all_books(cls):
query = cache.get_or_set(
'all_books',
cls.objects.all()
)
return query
现在我知道,每次运行Book.get\u all\u books()
时,它都会返回已缓存的结果。但是,如果我在shell中运行以下代码:
>>> list = Book.get_all_books()
>>> list[0].title # does this line hits the database?
>>> list[0].author # does this line hits the database?
>>> list.filter(title='for dummies') # does this line hits the database?
我错过了什么学习?你能给我指路吗?提前感谢您。您可以随时安装django调试工具栏并亲自查看 但是,应该清楚的是,Django不会针对缓存的内容访问数据库。在这里,您已经缓存了图书查询集。因此,该查询集上立即可用的任何内容都不会命中数据库。因此,将从缓存中提供
.title
;但是.author
是用户表的外键,其值不会被缓存,因此访问它会影响数据库
根据定义,调用
.filter()
始终意味着进行数据库查询。您可以安装django扩展,然后在安装的应用程序中注册它,然后在django shell中运行“python manage.py shell_plus--print sql”。
我认为您可以更好地理解查询是如何执行的