Django signal after the whole model has been saved

I have a Django model with 2 ManyToMany fields. I want to process data from the model every time it was saved.

The post_save signal post_save sent before it stores ManyToMany relationships, so I cannot use it. Then you have the m2m_changed signal, but since I have 2 ManyToMany fields, I canโ€™t be sure which ManyToMany field I should put the signal in.

Is there a signal that starts after all ManyToMany fields ManyToMany saved?

+7
source share
1 answer

I feel that the only way is to process the data after each m2m_change , as it does not seem to be an event or signal that compares โ€œall associated data of this model with storageโ€.

If this is a high cost, you can process the processing asynchronously. When I faced a similar situation, I added a model logical field to handle the processing-related state (e.g. MyModel.needs_processing ), and a separate asynchronous task queue (Celery, in my case) will go through every minute and process the processing reset / condition.

In your case, if m2m_changed and needs_processing is False , you can set needs_processing to True and save the model by marking it for processing according to your task queue. Then, even when the second m2m_changed triggered for another m2m field, this will not lead to duplication of processing costs.

+3
source

All Articles