9

I am working on a Django project and I want to send a signal when something gets added to some model's related set. E.g. we have an owner who has a set of collectables, and each time the method owner.collectable_set.add(something) is getting called, I want a signal like collectable_added or something. Signals are clear to me, but I don't know which manager(?) contains the "add" method that I want to override.

Edit for Xavier's request to provide more details: you can easily override a model’s save method, by simply defining it and calling the "super-save" so it gets properly saved with some extra functionality. But I wonder where to override a related set's add method.

Gosh, I think I haven't brought in any further details, but I think it should be clear what I want to do even from the first paragraph.

Edit 2: This is the method I want to override. Is it recommended to do so, or do you suggest another way to place the sending of the signal?

Pops
  • 30,199
  • 37
  • 136
  • 151
mamachanko
  • 886
  • 1
  • 7
  • 15
  • Your question is really vague. If you can provide a pseudo-code, or try to explain it better, I think more people could help. – Xavier Ho May 21 '10 at 10:53

3 Answers3

4

This is the solution I found, the m2m_changed signal. Took me quite some searching and reading. Furthermore, I found out that it is not trivial to extend the ManyRelatedManager class, which would have been the other option. But with the m2m_changed signal I can rely on built-in functions which is the preferred way most of the time.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
mamachanko
  • 886
  • 1
  • 7
  • 15
0

I think you're looking for the RelatedManager Class.

Ofri Raviv
  • 24,375
  • 3
  • 55
  • 55
  • Thanks for you reply. It looks like the solution, but i forgot to mention that i am dealing with a m2m-relation. So in this case the ManyRelatedManager class would be the one to extend or to insert the signal into. BUT it is not trivial to extend this class since it is dynamically generated. Thanks anyway. I'll post a solution i found but haven't tested. – mamachanko May 25 '10 at 10:12
0

After much searching (thanks to this Paul's hint), I came across this snippet that helped to explain the m2m_changed implementation to intercept not override the add method on the ManyRelatedManager. It appears that the manager on a many-to-many relationship happens on the fly, so it's not trivial to override the method.

Sean Chon
  • 397
  • 5
  • 13