Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django signal after whole model has been saved

I have a Django model with 2 ManyToMany fields. I want to process the data from the model each time it has been saved.

The post_save signal is sent before it saves the ManyToMany relations, so I can't use that one. Then you have the m2m_changed signal, but since I have 2 ManyToMany fields I cannot be sure on which ManyToMany field I should put the signal.

Isn't there a signal that is triggered after all the ManyToMany fields have been saved?

like image 819
gitaarik Avatar asked Apr 12 '13 12:04

gitaarik


1 Answers

I feel like the only option is to process the data after every m2m_change, since there doesn't appear to be an event or signal that maps to "all related data on this model has finished saving."

If this is high cost, you could handle the processing asynchronously. When I encountered a similar situation, I added a boolean field to the model to handle state as it related to processing (e.g., MyModel.needs_processing) and a separate asynchronous task queue (Celery, in my case) would sweep through every minute and handle the processing/state resetting.

In your case, if m2m_changed and needs_processing is False, you could set needs_processing to True and save the model, marking it for processing by your task queue. Then, even when the second m2m_changed fired for the other m2m field, it wouldn't incur duplicate processing costs.

like image 99
Jeremy Bowers Avatar answered Oct 06 '22 00:10

Jeremy Bowers