Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a related set's "add" method in Django

Tags:

django

set

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?

like image 1000
mamachanko Avatar asked May 21 '10 10:05

mamachanko


People also ask

How do I override a save in Django?

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.

How Django knows to update VS insert?

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.

Does create call save Django?

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.


1 Answers

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.

like image 146
mamachanko Avatar answered Oct 20 '22 23:10

mamachanko