0
0
Djangoframework~30 mins

Why caching matters for performance in Django - See It in Action

Choose your learning style9 modes available
Why caching matters for performance
📖 Scenario: You are building a simple Django web app that shows a list of popular books. Each time a user visits the page, the app fetches the book data from a slow database query. To make the page load faster, you want to use caching.
🎯 Goal: Build a Django view that caches the list of books for 60 seconds. This will reduce the number of slow database queries and improve page load speed.
📋 What You'll Learn
Create a list of book titles as initial data
Set a cache timeout variable for 60 seconds
Use Django's cache framework to store and retrieve the book list
Return the cached book list in the view response
💡 Why This Matters
🌍 Real World
Caching is used in real websites to speed up pages by storing data temporarily, so users get faster responses without waiting for slow database queries every time.
💼 Career
Understanding caching is important for backend developers to optimize web app performance and reduce server load.
Progress0 / 4 steps
1
Create the initial book list data
Create a variable called book_list that contains this exact list of strings: ["The Hobbit", "1984", "Pride and Prejudice"]
Django
Need a hint?

Use a Python list with the exact book titles inside square brackets.

2
Set the cache timeout duration
Create a variable called cache_timeout and set it to the integer 60 to represent 60 seconds
Django
Need a hint?

Just assign the number 60 to the variable named cache_timeout.

3
Use Django cache to store and retrieve book list
Import cache from django.core.cache. Then write a function called get_books() that tries to get book_list from cache with key 'books'. If not found, it sets the cache with book_list and cache_timeout, then returns the list.
Django
Need a hint?

Use cache.get('books') to try fetching cached data. If it returns None, use cache.set('books', book_list, cache_timeout) to save it.

4
Complete the Django view to return cached books
Write a Django view function called book_view that calls get_books() and returns an HttpResponse with the book titles joined by commas. Import HttpResponse from django.http.
Django
Need a hint?

Use HttpResponse to send the book titles as a comma-separated string.