You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

45 lines
1.7 KiB

# hadith_app/signals.py
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.core.cache import cache
from .models import *
# 1. Define all models that affect the list
# If a Category title changes, the list must update.
# If a Status changes, the list must update.
TARGET_MODELS = [
Hadis, HadisCategory, HadisCollection, HadisCorrection, HadisInCollection, HadisReference,
HadisSect, HadisStatus, HadisTag, HadisTransmitter, Transmitters, TransmitterOpinion, TransmitterReliability,
TransmitterOriginalText, ReferenceImage, BookReference, BookAttribute, BookAuthor, BookReferenceImage,
NarratorLayer, OpinionStatus, ContentRelease,
CorrectionReference, BookEdition, BookVolume, CorrectionReferenceImage
]
def invalidate_hadis_cache():
"""
Deletes all Redis cache keys matching '*hadis_api*'.
Falls back to cache.clear() if cache backend doesn't support delete_pattern.
"""
try:
if hasattr(cache, 'delete_pattern'):
deleted = cache.delete_pattern("*hadis_api*")
print(f"Cache cleared for hadis_api (deleted {deleted} keys)!")
else:
cache.clear()
print("Cache cleared for hadis_api (fallback clear)!")
except Exception as e:
# Fail silently or log error, don't crash the transaction
print(f"Cache clear failed: {e}")
@receiver(post_save)
@receiver(post_delete)
def clear_hadis_cache(sender, instance, **kwargs):
"""
Clears the API cache whenever a Hadith or related model is saved/deleted.
"""
if sender in TARGET_MODELS:
invalidate_hadis_cache()
print(f"Cache cleared for {sender.__name__} update!")