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?
save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically.
The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.
create() will automatically save, so even if you fix your error - you will still have to make sure the arguments to create fulfill the database requirements to save a record.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With