I'm using redis for caching data on my project and delete the cache through the signal. Whenever there is a change on my database the signal clear the cache using the key provided as follow:
@receiver(post_save, sender=Book)
def cache_clean_books(sender, instance, created, **kwargs):
if created:
cache.delete("all_books")
else:
cache.delete(f'book_id_{instance.id}')
Everything is working fine from here but when I use python manage.py flush to clear data from the database my signal is not triggered. Is there any way I can use to hit the signal whenever I flush data in django please?
The post_save
signal won't be called here since running python manage.py flush
doesn't act on the model instance, it simply executes SQL to flush the database. You can use the post_migrate
signal if you want to run code whenever the flush
command is run:
from django.db.models.signals import post_migrate
@receiver(post_migrate)
def clear_cache(sender, **kwargs):
# Clear your cache here
pass
Note: This will also run whenever you run a migration but I guess it can be safely assumed that a migration to the database should probably clear the cache.