0

My issue is similar to a few other questions asking about handling M2M fields when saving an object, eg. Django accessing ManyToMany fields from post_save signal
Django: Using signals to save a ManyToMany field

Basically, in order to work with M2M fields you need to listen for m2m_changed rather than post_save.

The problem I have is that I want my operations to occur only when creating a new object -- post_save gets a created argument, but as far as I can tell there's nothing similar for m2m_changed, and by the time the m2m_changed signal is triggered the object has been saved and given a PK, so there's no way to tell from the signal handler whether it's a newly created object or an existing object that was updated.

Is there any way around this?

Community
  • 1
  • 1
Adam
  • 938
  • 1
  • 8
  • 22
  • Very curious to know the usecase, because it might be the case that what you are trying to achieve can be done in the `post_save` signal itself. Moreover, m2m is specifically called _after_ the action (post_save, pre_save, etc.. ) – karthikr Sep 06 '14 at 03:16

1 Answers1

0

Workaround: - You can use the post_save method with a variable assigned to the model. For instance, you can set a variable to "created" when object is created. Then you can tell the model, to do something only if that variable is set to created. Once it performs operations, you can set that variable to "updated". Then the operations will not trigger in the handler.

OR

  • you can setup the joined model with the "through" function. That way you create the join table that Django does automatically and performs actions based on that model.
Özer
  • 2,059
  • 18
  • 22