Hello Django Fellows.
Being fairly new to Django, I ran across an issue recently which is driving me nuts. I figured i might use some help there. To quote my question on stack overflow :
I have a Django app that broadcasts changes of some of its models to its clients, to keep them up-to-date.
I have a separate app for that, that binds to the
post_save signal of these models and triggers the broadcast. (btw: i am aware that over-using signals is an anti-pattern, but in this case it seems like a good way for me to keep coupling low between the “live” app and the other apps)
Problems have come with models with
ManyToManyFields. I am not very familiar with Django’s handling of this but I understand that these fields are actually updated after the model is saved, due to the underlying relation table.
I was able to use the
m2m_changed signal to react to the
post_* actions and dispatch the broadcast after the object is all up-to-date. However, in the
post_save handler, I still need to detect that the m2m field is going to be mutated, to avoid broadcasting incomplete data and confusing the clients. How can I detect this , either in the
post_save signal handler or the model’s
save method ? Is there a way to raise a flag on an object when a m2m field is about to be mutated ?
Here’s what I’ve tried :
- Handle the
pre_*actions of the
m2m_changedsignal to detect incoming mutation of the field but that does not work, because the signal gets fired after
post_save, which is too late (incomplete data has already been broadcasted).
- Store initial values when the model instance is created, and compare them in the overriden
savemethod to look for changes. This does not work because the fields are not changed (yet) and report to be == the initial value ; plus I read on other questions that this practice could cause race conditions.
I’m looking forward for your help. Thanks a lot in advance.