3

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?

MohitC
  • 4,541
  • 2
  • 34
  • 55
Myzel394
  • 1,155
  • 3
  • 16
  • 40

1 Answers1

6

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

EdCornejo
  • 741
  • 13
  • 14
  • Thank you. I setup everything like you said. I cache an url with `cache_page` and a special `key_prefix`. When I use the same key to clear the cache (by using `cache.delete()` it doesn't seem to clear it. If I debug it in shell, I also don't get a value when using `cache.get()`. Do you have an idea? – Myzel394 Apr 14 '20 at 21:24
  • Are you sure that you cache is working? review you configuration. [Example](https://realpython.com/caching-in-django-with-redis/) – EdCornejo Apr 15 '20 at 04:10
  • It does work. Do `cache_page` and `cache.get` rely on the same cache? In the cache table I can see some key values like `views.decorators.cache.cache_page`. Do I have to use these to select my view caching? (even though this doesn't seem like good practice) – Myzel394 Apr 15 '20 at 09:30
  • If you use cache_page yes, other alternative is generate cache only of the variables (context that you send to render en el template) and not of the rendered page, I think that is more easy for you clear your cache using [Low level cache](https://django-book.readthedocs.io/en/latest/chapter15.html#the-low-level-cache-api) – EdCornejo Apr 15 '20 at 15:02
  • unfortunately `save()` is not the only method that can mutate a db row. `create`, `delete`, the bulk operations. some of these have their own signals, but some don't trigger a signal at all. – minusf Jan 27 '23 at 09:53