I have an Apscheduler job that updates the active field in my subscription model and sets it to False. I created a post_save signal that should be triggered when the subscription model is updated, but it doesn't work. Here's my code.
--job.py--
from django.conf import settings
from subscription.models import AccountSubscription
from django.utils import timezone
def schedule_api():
try:
data = {'is_active':False}
AccountSubscription.objects.filter(expiry_date__lte=timezone.now(), is_active=True).update(**data)
except Exception:
pass
-- signals.py--
@receiver(post_save, sender=AccountSubscription)
def post_save_user_subscription_expired(sender, instance, created, **kwargs):
"""Notifies users of subscription expiration."""
try:
if not created:
if not instance.is_active:
print("Notified users")
except Exception as ex:
print(ex)
# context = {
# 'status': 'error',
# 'message': 'A subscription expiration notification error has occurred.'
# }
# raise exceptions.ParseError(context)
Please is there something that I am doing wrongly?
update method does not call the save method and does not trigger signals. Cause Django makes a direct SQL query
It is documented: https://docs.djangoproject.com/en/4.1/ref/models/querysets/#update
The solution is to make a loop for updating each instance directly or move the notify business logic into a function and call it after your updating query.