开发者

Django: Sending Signals - Not understanding the documentation

开发者 https://www.devze.com 2023-01-14 16:07 出处:网络
I have 2 listeners defined: def update_dashbaord_modified_date(sender, **kwargs): \"\"\"Listen for changes to Goal, Action, etc. since we

I have 2 listeners defined:

def update_dashbaord_modified_date(sender, **kwargs):
    """Listen for changes to Goal, Action, etc. since we
    want to update the date modified on Dashbaord when a change occurs."""
    ... do something ...

post_save.connect(update_dashbaord_modified_date) # Register to listen for post_save signals
post_delete.connect(update_dashbaord_modified_date) # Register to listen for post_delete signals

And now, after there is a change to a Goal or adds a Goal (model class Goal), I want that save to send a si开发者_JAVA百科gnal. How is this implemented. I don't understand the documentation for it.

Thanks


  1. Define your signals in your_app/signals.py (App that raise Signal, not listen)

    from django.dispatch import Signal
    my_signal = Signal(providing_args=["instance", "args", "kwargs"])

  2. in your model/view, from where you want raise signal

    ...do some processing
    my_signal.send(sender=self.__class__, args, kwargs)
    # kwargs contains type of action, in your case
    # action= 'Added'|'Modified'|'Deleted",

  3. some where else in code (where ever you want to listen)

    my_signal.connect(this_is_my_call_back_method)


From the django docs:

Where should this code live?

You can put signal handling and registration code anywhere you like. However, you'll need to make sure that the module it's in gets imported early on so that the signal handling gets registered before any signals need to be sent. This makes your app's models.py a good place to put registration of signal handlers.

You can import update_dashbaord_modified_date in you models.py and after the class definition add your method to the post_save and post_delete handlers.

from signals import update_dashbaord_modified_date
class myModel(models.Model):
     stuff
post_save.connect(update_dashbaord_modified_date) 
post_delete.connect(update_dashbaord_modified_date)
0

精彩评论

暂无评论...
验证码 换一张
取 消