Login

Cached lookup model mixin

Author:
isagalaev
Posted:
January 22, 2008
Language:
Python
Version:
.96
Tags:
foreignkey cache lookup parent
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. Generic Model by hakejam 8 years, 4 months ago
  2. Allow filtering and ordering by counts of related query results by exogen 8 years, 2 months ago
  3. Many 2 Many Admin Ordering with Mysql by visik7 1 year, 10 months ago
  4. Querying on existence of a relationship by ubernostrum 7 years, 11 months ago
  5. Ordered items in the database - alternative by Leonidas 8 years, 1 month ago

Comments

Please login first before commenting.