Using Django Signals With Many-To-Many relationships
Sometimes it is useful to perform an action after something has been added to a many-to-many model in Django. The offical Django documentation is pretty sparse on this topic, so I figured I would document a decent solution. In the top of your models.py file, import Django signals.
Let says your models are setup as follows:
And now lets say you want to perform some action, say send an email, everytime a new event is added to the contact.events attribute. The code that will do this looks like this:
m2m_send_email will get called every time you call contact.events.add(event); contact.save(). You can decide which action you want to support and when to send the email by checking kwargs['action'].