Dan Goldin
Dan Goldin

Reputation: 977

Django Caching - How do I set up my code to avoid duplicating cache logic?

I started profiling my app and discovered that there's a piece of code that takes a significantly longer amount of time to complete than others. In the view, I'm retrieving some data from a database and transforming it a little bit. In the template, there's a filter that will take this transformed data and convert into a HTML.

I realized that I could leverage caching since this component does not change that frequently but I'm wondering what the best way to do it is. I can cache both the results of the database call/transform but I can also cache the template fragment. It seems odd that I'd need to cache two things to get the best effect so I imagine my code should have been structured differently so I would only need to cache the data in one location.

One idea I had is to do the database call from within the template filter function but I've been trying to keep my model code outside of my template filters.

What is the best way to handle this sort of problem?

Upvotes: 4

Views: 349

Answers (2)

okm
okm

Reputation: 23871

If the transformation can be represented as complex queryset, you could evaluate it in template w/o caching in view. If not, you could

  • do the logic in template tag inside cache block
  • wrap logic and pass it to render, typically in the form of closure or model method
  • only do view cache, as long as rendering process is simple
  • check possibility of SSI w/ help of TemplateResponse
  • write code to check-and-use template cache in view, w/ considering of possible race-write and dog-pile issue.

Furthermore, for queryset cache, you could try johnny-cache, as well as django-cache-machine.

Upvotes: 1

ygneo
ygneo

Reputation: 412

You don't need to cache in the view AND in the template fragment. The idea of caching is, once you've something cached, you get it from cache until the cache key expires.

Caching the database results in the view implies writing some code specific for the view logic, that you'd probably need to change every time the logic changes.

Caching the template fragment is a better approach, because even if you change the template "logic", as long as you keep the fragment inside a cached block, the caching will continue working.

Also IMHO, the more close to the final response you cache, the more reliable the cache logic will be.

Upvotes: 0

Related Questions