Search code examples
pythondjangodatabasecachingmemcached

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


I'm having trouble to understand how to properly use the Caches Framework. lets say I have this code:

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

now I know that every time I run Book.get_all_books() it returns the already cached result. but what if I run this code in 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?

what have I missed to study? can you please guid me? thank you in advance.


Solution

  • You could always install django-debug-toolbar and see for yourself.

    However, it should be clear that Django will not hit the database for things that are cached. Here you have cached the Books queryset. Therefore, anything that is immediately available on that queryset will not hit the database. So .title will be served from the cache; but .author is a foreign key to the User table, whose values are not cached, so accessing it will hit the database.

    Calling .filter() always means making a database query, by definition.