djangodjango-signalsm2m

How to not trigger `m2m_changed` signal when updating many to many relationship in Django?


The Use Case

In my case, I have two signals that are listening on two 2 m2m fields, each of those fields are in different models. The problem happens when one signal is triggered, it triggers the other signal and vice versa, which will result in a recursive loop which will never ends. I need a convenient way to run one signal without triggering the second signal.

Understand More

If you are curious to know how this case could happen: I have two models which I need to make them mutually synced; if I updated the m2m field in the one model, I need those changes to be reflected on another m2m field in another model and vice versa.


Solution

  • The solution is to use set instead of: add, remove, or clear. Because all of these trigger m2m_changed signal multiple times.

    This is not mentioned in the documentation talking about set or the part talking about m2m_changed