skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. you can install django-extensions and then register it inside installed app and then run "python manage.py shell_plus –print-sql" inside django shell.
    I think you can better understand how your query executing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search