Django signal mechanism details

  • 2020-05-30 20:34:26
  • OfStack

Django provides a signaling mechanism. This is the observer mode, also known as publish-subscribe (Publish/Subscribe). When an action occurs, a signal is sent, and the function that listens for the signal executes.

Django has some built-in signals, such as:


django.db.models.signals.pre_save  In a certain Model Save the previous call 
django.db.models.signals.post_save  In a certain Model Call after saving 
django.db.models.signals.pre_delete  In a certain Model Call before delete 
django.db.models.signals.post_delete  In a certain Model Call after deletion 
django.core.signals.request_started  The establishment of Http Send on request 
django.core.signals.request_finished  In the closed Http Send on request 

All we need to do is register an receiver function. For example, if you want to print 1 line after each request is completed.

Callbacks can be used to register:


# receiver
def my_callback(sender, **kwargs):
  print("Request finished!")
 
# connect
from django.core.signalsimport request_finished
 
request_finished.connect(my_callback)

You can also use decorator to register, and the following code is completely equivalent to the one above.


from django.core.signalsimport request_finished
from django.dispatchimport receiver
 
@receiver(request_finished)
def my_callback(sender, **kwargs):
  print("Request finished!")

In addition to using sender, the receiver callback function can also use some other parameters, such as the pre_save function:

sender: sender (model class if pre_save)
Examples of instance:
raw
using
update_fields
post_save() is a utility function that supports some linkage updates. We don't have to write it in view every time. For example, if a user submits a refund application, we need to change the status of the order to the "refunded" status. You can use the signaling mechanism without having to modify everything.


@receiver(post_save, sender=RefundForm)
deforder_state_update(sender, instance, created, **kwargs):
  instance.order.state = REFUNDING
  instance.order.save() #  Here, order is refundform the 1 A foreign key 

Of course, there can be more comprehensive here, such as refund form cancelled to change back to the status.

The observer is a very useful design pattern, and Django also supports user-defined signals.


Related articles: