当您从缓存查询中请求对象的属性时,django 会访问数据库吗?

Does django hits the database when you request for an object's attribute from a cached query?

我无法理解如何正确使用缓存框架。假设我有这个代码:

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_all_books() 它 returns 已经缓存的结果。但是如果我 运行 这个代码在 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-debug-toolbar 并亲自查看。

但是,应该清楚 Django 不会为缓存的内容访问数据库。在这里您缓存了 Books 查询集。因此,该查询集上立即可用的任何内容都不会访问数据库。所以 .title 将从缓存中获取;但是 .author 是用户 table 的外键,其值未被缓存,因此访问它会命中数据库。

根据定义,调用 .filter() 总是意味着进行数据库查询。

你可以安装 django-extensions 然后在安装的应用程序中注册它然后 运行 "python manage.py shell_plus --print- sql" 在 django shell 中。 我认为您可以更好地理解查询的执行方式。