Search code examples
djangodjango-cachedjango-caching

Django Cache - Update when model changed


I can't seem to find any tutorial on how to do this.

So, I basically want to add caching to my Django project. I made a blog view, that should be cached and updated only if the model got changed since last caching.

How do I do this?


Solution

  • You could clear the cache after creating or updating the object using signal post-save signal

    from django.db.models.signals import post_save
    from django.dispatch import receiver
    
    class Entry(models.Model):
        content = models.TextField()
    
    # method for updating after entry save data
    @receiver(post_save, sender=Entry)
    def clear_cache(sender, instance, **kwargs):
        # call cache clear here
    

    Another alternative is to overload the save method of the model and after saving it calls to cache clear