Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 5 of 10 · Django Performance & Optimization
Interview question

How does Django's per-view and per-site caching work, and when should you use low-level cache API instead? Django की प्रति-व्यू और प्रति-साइट कैशिंग कैसे काम करती है, और लो-लेवल कैश API का उपयोग कब करना चाहिए?

Answer

Django offers caching at several granularities. Per-site caching (UpdateCacheMiddleware + FetchFromCacheMiddleware) caches every GET/HEAD response for the whole site, simplest to enable but too coarse for pages with any personalized or frequently-changing content. Per-view caching with @cache_page(timeout) caches the rendered output of one specific view, better suited to pages that are the same for every visitor, like a public blog post.

The low-level cache API (cache.get(), cache.set()) gives full manual control to cache anything — a single expensive queryset result, a computed aggregate, an external API response — independent of the request/response cycle, which is necessary whenever only part of a page needs caching or the cached value needs custom invalidation logic tied to specific data changes.

from django.core.cache import cache
from django.views.decorators.cache import cache_page

@cache_page(60 * 15)
def blog_post(request, slug): ...

def get_top_products():
    result = cache.get('top_products')
    if result is None:
        result = list(Product.objects.order_by('-sales')[:10])
        cache.set('top_products', result, timeout=3600)
    return result

Django कई स्तरों पर कैशिंग प्रदान करता है। प्रति-साइट कैशिंग पूरी साइट के लिए हर GET/HEAD रिस्पॉन्स को कैश करती है, सक्षम करना सबसे आसान लेकिन किसी भी पर्सनलाइज़्ड कंटेंट वाले पेजेज़ के लिए बहुत मोटा। @cache_page(timeout) के साथ प्रति-व्यू कैशिंग एक विशिष्ट व्यू के रेंडर्ड आउटपुट को कैश करती है।

लो-लेवल कैश API (cache.get(), cache.set()) किसी भी चीज़ को कैश करने के लिए पूर्ण मैन्युअल नियंत्रण देता है।

@cache_page(60 * 15)
def blog_post(request, slug): ...

def get_top_products():
    result = cache.get('top_products')
    if result is None:
        result = list(Product.objects.order_by('-sales')[:10])
        cache.set('top_products', result, timeout=3600)
    return result

Was this answer clear?