extra_context caching data?

August 12, 2008 08:30.38 PM

If you're using Django out there and you happen to use the extra_context variable for your generic templates, you might have noticed that the querysets are being cached and not updated unless you restart your server. The problem is that querysets will be cached by definition of the extra_context dictionary unless they are callable functions. See the example below as it applies to my sidebar.

def get_books():
return Book.objects.filter(status='S').order_by('-post_date')[:3]

def get_albums():
return Album.objects.filter(status='S').order_by('-post_date')[:3]

def get_dvds():
return DVD.objects.filter(status='S').order_by('-post_date')[:3]

def get_blogrolls():
return BlogRoll.objects.order_by('-last_name')

info_dict = {
'queryset': Post.objects.filter(status='P').order_by("-pub_date"),
'date_field': 'pub_date',
'extra_context':{ 'books' : get_books,
'albums' : get_albums,
'dvds' : get_dvds,
'blogrolls' : get_blogrolls,
'form':form,
},
}

Comments

Jeremy Carbaugh
August 12, 2008 10:55.31 PM

Another solution is to use template tags to render the common sidebar items. Recent versions of trunk also include the ability to cache specific chunks of templates. Template tags + caching provides a really nice way of isolating the functionality and preventing unnecessary database calls.

Post a comment

  • So to keep out the annoying people that try to sell Viagra or Porn on my site, please fill out the Captcha so your comments get through. Props to Carbauja since I stole his entire comment interface and back end.

A Django site.