I have an app that has a 'real-time data' frontend by using django signals and webhooks. It works when a relationship is removed, or added, but if a relationship instance is deleted, m2m_changed isn't fired so the frontend isn't updated. Is m2m_changed meant to be fired in this situation though?
The parent model has an m2m field which stores 'subscribed to' child models. I also have a property function that shows all possible child models to subscribe to (I have both subscribed and unsubscribed fields so i can have an on/off switch on the frontend):
class Parent(models.model):
subscribed_to = m2mField(Child)
@property
def potential_subscriptions(self):
return Child.objects.all() # not sure if this is bad practice
My signal looks like this:
@receiver(m2m_changed, sender=Parent.subscribed_to.through)
def signal(sender, instance, action, reverse, **kwargs):
from .api.serializers import ParentSerializer
if action == "post_add" or action == "post_remove" or action == "post_clear":
serializer = ParentSerializer(instance)
websocket.send(f"parent_{instance.id}", "parent_update", serializer.data)
So it works when child instances are added or removed, but if a child instance is deleted it doesn't fire, so my websocket doesnt update the frontend.
As a work around I tried to create a pre_delete signal for the Child object, and within the signal I clear it's relationship before it is deleted to force the Parent m2m signal to fire. This way does tell the frontend that the child has been unsubscribed to, but the Child is still within the potential_subscriptions data field because this is all fired in the Childs pre_delete signal. The frontend is updated before the child is deleted, so the frontend still believes the child exists when it doesn't.
Is there a way to re-logic my signals to get the desired outcome? Or maybe i will have to reconstruct my model?