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

浪子不回头ぞ 提交于 2019-12-10 13:37:59

问题


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?


回答1:


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.




回答2:


I think you're looking for the RelatedManager Class.




回答3:


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.



来源:https://stackoverflow.com/questions/2881368/how-to-override-a-related-sets-add-method-in-django

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!