Login

Cached lookup model mixin

Author:
isagalaev
Posted:
January 22, 2008
Language:
Python
Version:
.96
Score:
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()[0] in ('pk', pk_name, '%s__exact' % pk_name) and self._cache.get(kwargs.values()[0], False)
        if value:
            return value
        else:
            super(CachedGet, self).get(*args, **kwargs)

# Usage:

class MyModel(CachedGet, models.Model):
    # ...

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.