Removing specific items from Django's cache?

后端 未结 2 1788
既然无缘
既然无缘 2021-02-03 12:21

I\'m using site wide caching with memcached as the backend. I would like to invalidate pages in the cache when the underlying database object changes.

If the page name

2条回答
  •  梦如初夏
    2021-02-03 12:49

    I haven't done a lot of caching with Django, but I think what you want here are signals.

    You can set up a post_save signal on the underlying object, and have the callback function invalidate that page in the cache.

    from django.core.signals import post_save
    from django.core.cache import cache
    
    def invalidate_cache(sender, **kwargs):
        # invalidate cache
        cache.delete(sender.get_absolute_url()) # or any other pertinent keys
    
    post_save.connect(invalidate_cache, sender=UnderlyingModel)
    

    This should properly remove the item from the cache when it is updated.

提交回复
热议问题