This mixin is intended for small lookup-style models that contain mostly static data and referenced by foreign keys from many other places. A good example is a list of Payment options in an e-shop that is referenced from Orders and is hitting database
order.payment at least one time for an order.
The idea is to cache entire table in a dict in memory that will live for entire life of a whole process serving many requests.
The downside is that you need to restart the server when a cached lookup table changes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Mixin: class CachedGet(object): def get(self, *args, **kwargs): pk_name = self.model._meta.pk.name if not hasattr(self, '_cache'): self._cache = dict((obj._get_pk_val(), obj) for obj in self.all()) value = len(kwargs) == 1 and kwargs.keys() in ('pk', pk_name, '%s__exact' % pk_name) and self._cache.get(kwargs.values(), False) if value: return value else: super(CachedGet, self).get(*args, **kwargs) # Usage: class MyModel(CachedGet, models.Model): # ...
More like this
- codigo alto nivel by MrRocklion 2 days, 14 hours ago
- Load template from specific app by Krzysiek555 3 weeks, 2 days ago
- PostgreSQL JSON subqueries by dolamroth 3 weeks, 4 days ago
- "Magic Link" Management Command by webology 6 months ago
- Closest ORM models to a latitude/longitude point by simonw 6 months ago