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

More like this

  1. Clone model mixin by zakj 3 years, 4 months ago
  2. ModelList class by facundo_olano 1 year, 2 months ago
  3. Ordered items in the database - alternative by Leonidas 4 years, 11 months ago
  4. Run and cache only one instance of a heavy request by farnsworth 1 year, 9 months ago
  5. RelatedMixin for Details and Updates with Related Object Lists by christhekeele 3 days, 6 hours ago

Comments

(Forgotten your password?)