Can Django pre_save signal work for all derived classes
-
26-09-2019 - |
Question
I have a model class "Action" that get's extended by several other classes. I am new to django and assumed that if I called pre_save.connect(actionFunc, sender=Action) that actionFunc would get called anytime the save method in the Action class was called (including by any derived class).
My observation is that this function only gets triggered when the instance is a direct match of the Class type defined in Sender. Is there anyway to get this to recieve signals for all derived instances of Action as well?
Solution
No, you have to call the pre_save.connect
as many number of times.
However, you can use python to get all the classes that extend the class of your interest, and loop over the pre_save connect statement.
Say, if the extended classes of the Action
are all in a given file, you can do the following:
global_dict = globals().copy()
[el for el in global_dict.values() if getattr(el,'__base__',None)==Action]
OTHER TIPS
one thing you can do is modify the signal sender in django so that instead of matching against a specific type it instead does
if isinstance(sender, filter):
send_signal()
(pseudocode)