- January 22, 2008
- foreignkey cache lookup parent
- 0 (after 0 ratings)
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
- Generic Model by hakejam 9 years, 5 months ago
- Allow filtering and ordering by counts of related query results by exogen 9 years, 3 months ago
- Many 2 Many Admin Ordering with Mysql by visik7 2 years, 11 months ago
- Querying on existence of a relationship by ubernostrum 8 years, 12 months ago
- Ordered items in the database - alternative by Leonidas 9 years, 1 month ago