from django.db.models.signals import post_save, post_delete, m2m_changed from django.dispatch import receiver from utils.cache import invalidate_cache_patterns from .models import Author, Book, BookCollection, Category TARGET_MODELS = [Author, Book, BookCollection, Category] def invalidate_library_cache(): """ Invalidates all Redis cache keys for library API views. """ return invalidate_cache_patterns("*library_api*", "*library_books*") @receiver(post_save) @receiver(post_delete) def clear_library_cache_on_save_or_delete(sender, instance, **kwargs): if sender in TARGET_MODELS: invalidate_library_cache() @receiver(m2m_changed) def clear_library_cache_on_m2m(sender, instance, action, **kwargs): if action in ('post_add', 'post_remove', 'post_clear'): if isinstance(instance, (Book, BookCollection, Category)): invalidate_library_cache()