2

I have some Django simple manager functions where I'd like to cache the response (using Memcached), and invalidate these on model save/delete. I thought there'd be a standard solution for this in the Django community, but I can't find one, so would like to check I'm not reinventing the wheel.

Here's an example with a possible solution using django-cache-memoize

from cache_memoize import cache_memoize
from django.utils.decorators import method_decorator
from django.db.models.signals import post_save, post_delete
from django.conf import settings


class MyModel(Model):
   name = models.CharField()
   is_live = models.BooleanField()

   objects = MyModelManager()


class MyModelManager(Manager):
   @method_decorator(cache_memoize(settings.CACHE_TTL, prefix='_get_live'))
    def _get_live(self):
        return super().get_queryset().filter(is_live=True)

    def example_queryset():
        return self._get_live()


# Cache invalidation
def clear_manager_cache(sender, instance, *args, **kwargs):
        MyModel.objects._get_live.invalidate(MyModel) 

post_save.connect(clear_manager_cache, sender=MyModel, weak=False)
post_delete.connect(clear_manager_cache, sender=MyModel, weak=False)

This seems to work, but strikes me as quite a lot of boilerplate for something that's a pretty standard Django pattern/use-case.

Are there any simpler solutions out there to achieve a similar thing?

MDalt
  • 1,681
  • 2
  • 24
  • 46

0 Answers0