Skip to content

Instantly share code, notes, and snippets.

@harmo
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harmo/6160d62ad165df636f14 to your computer and use it in GitHub Desktop.
Save harmo/6160d62ad165df636f14 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from django.db import models
from django.core.cache import cache
from django.db.models.query import QuerySet
from utils import key_for_instance
class CachedQuerySet(QuerySet):
def get_pk(self, kwargs):
for val in ('pk', 'pk__exact', 'id', 'id__exact'):
if val in kwargs:
return kwargs[val]
return None
def filter(self, *args, **kwargs):
pk = self.get_pk(kwargs)
if pk is not None:
key = key_for_instance(self.model, pk=pk)
cache_content = cache.get(key)
if cache_content is not None:
self._result_cache = [cache_content]
return super(CachedQuerySet, self).filter(*args, **kwargs)
class CacheManager(models.Manager):
def get_queryset(self):
return CachedQuerySet(self.model)
####################################################
class CacheableModel(models.Model):
class Meta:
abstract = True
def save(self, *args, **kwargs):
super(CacheableModel, self).save(*args, **kwargs)
cache.set(key_for_instance(self), self, 60 * 60 * 24)
def delete(self):
cache.delete(key_for_instance(self))
super(CacheableModel, self).delete()
objects = CacheManager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment