[Answered ]-Python Django cache vs store in model field? Which is more efficient?

2đź‘Ť

âś…

A cache is a cache is cache, however you implement it, and the main problem with caches is invalidation.

As Melvyn rightly answered, the case for the cache framework is that it’s (well, can be, depending on which backend you choose) outside your database. Whether it’s a pro or cons really depends on your database load, infrastructure and whatnots… if you already use the cache framework (for more than plain unconditional full-page caching I mean) and want to mimimize the load on your database then it’s possibly worth the added complexity.

Else storing your computed result in the db is quite straightforward and doesn’t require additional servers, install etc. I’d personnally go for a dedicated model – to avoid unnecessary overhead at the db level -, including both the cached result and a checksum of the params on which this result depends (canonical memoization pattern) so you can easily detect whether it needs to be recomputed. I found this solution to be easier to maintain than trying to detect changes to each and any of those params and invalid/recompute the cache “on the fly” (which is what can make proper cache invalidation difficult or at least complex to implement) but this again depends on what those params are and where they come from.

0đź‘Ť

The upside to using the cache framework is that you don’t have to use the database. You can scale your cache store independent of your database and run the cache on different physical (or virtual) machines.

In addition you don’t have to implement the stale vs fresh logic, but that’s a one-off.

👤user1600649

0đź‘Ť

4-5 times a week doesn’t look like a big challenge, but nobody knows except you what kind of computation do you have, how many data you should store, how many users do you have and so on.
If you want to implement this with TextField, it still some kind of caching system, so I suggest to use django’s caching system with database backend first https://docs.djangoproject.com/en/1.11/topics/cache/#database-caching You can’t retrieve data with 1 query like in case of TextField, but later you can replace database with other layer if necessary.

Leave a comment