Question

I have a Django application and a postgres backend. It's essentially a search site with a large database, and the data typically changes once a day. I would like to start caching, to reduce load on the database.

I've set up memcached, but I have the following architecture in my views, designed to let my app use Ajax in the front-end:

@cache_page(60 * 60 * 12)
def items(request, pattern=None, specialurl=None):
  if request.is_ajax():
    template = "result_ajax.html"
  else: 
    template = "index.html"

.. and unfortunately, the combination of caching plus special handling of Ajax calls does not work well.

This is beacuse memcached doesn't distinguish between the Ajax results and the non-Ajax results - so Ajax calls from the front-end are given cached non-Ajax results, and vice versa.

So what I need to do is to figure out how else to cache. I can think of the following options:

  1. Cache only the database queries, for up to a day at a time. Is this possible?
  2. Cache the fragment of the template within result_ajax.html that actually displays the results. (index.html actually includes result_ajax.html.)

Which of these is likely to be the best way to do things?

Was it helpful?

Solution

I would try something like this tell the cache decorator to use a different cache key for Ajax and non-Ajax requests:

from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_headers

@cache_page(60 * 60 * 12)
@vary_on_headers('X-Requested-With')
def items(request, pattern=None, specialurl=None):
  if request.is_ajax():
    template = "result_ajax.html"
  else: 
    template = "index.html"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top