Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Automatically invalidate cache when data changes via Admin panel?

Tags:

caching

django

On a roll with Django questions today.

The caching framework looks pretty awesome and I'd like to use it sitewide. Rather than set an explicit expiry time for my views, I'd prefer to cache them indefinitely and only invalidate/delete the cache when the content changes. Dream scenario, right?

Is there some way to hook into Django's automatic admin so that when a CRUD operation happens, the relevant cache gets deleted? I expect I'd have to somehow tell the admin panel which model should invalidate which class, but in principle, is this possible? Some kind of callback I can add? Any alternatives?

thanks! Matt

like image 791
Matt Andrews Avatar asked Apr 30 '11 15:04

Matt Andrews


1 Answers

Two part answer:

  1. Clear cache on a CRUD event? Easy as pie — use Django signals.

  2. Clear only the relevant parts of the cache? This is a genuinely hard problem. On the surface it may look straightforward, but the dependencies can be very difficult to discern for all but the most trivial cases.

We sort of solved part 2 by extending the django caching code to embed object class/id info into the name, and then caching at a sub-page level. On a CRUD event we could do a simple regexp through the cached item names and prune as needed.

All in all, I think it was yet another case of Premature Optimization and it's not at all clear that it made any difference. Next time I'll wait until there is a proven, measurable performance problem before doing something like this.

like image 77
Peter Rowell Avatar answered Sep 27 '22 19:09

Peter Rowell