Cached lookup model mixin

 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):
    # ...

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.