Django signal mechanism details, django signal details
Django provides a signal mechanism. It is actually the observer mode, also called Publish-subscription (Publish/Subscribe ). When some actions occur, the function that sends a signal and then listens to the signal is executed.
Django has some built-in signals, such:
Django. db. models. signals. pre_save call django before a Model is saved. db. models. signals. post_save: Call django after a Model is saved. db. models. signals. pre_delete calls django before a Model is deleted. db. models. signals. post_delete: Call django after a Model is deleted. core. signals. request_started sends django when an Http request is created. core. signals. request_finished is sent when an Http request is disabled
All we need to do is register a handler function. For example, to print a line after each request is complete.
You can use the callback Method for registration:
# receiverdef my_callback(sender, **kwargs): print("Request finished!") # connectfrom django.core.signalsimport request_finished request_finished.connect(my_callback)
You can also use the decorator to register. The following code is equivalent to the above Code.
from django.core.signalsimport request_finishedfrom django.dispatchimport receiver @receiver(request_finished)def my_callback(sender, **kwargs): print("Request finished!")
In addition to sender, the handler callback function can also use other parameters, such as the pre_save function:
Sender: the sender (if it is pre_save, It is model class)
Instance: instance
Raw
Using
Update_fields
Post_save () is a more practical function that supports coordinated updates. Instead of having to write them in the view every time. For example, if a user has submitted a refund application, we need to change the status of the order to "refunded. You can use the signal mechanism without having to modify it in every place.
@ Author Er (post_save, sender = RefundForm) deforder_state_update (sender, instance, created, ** kwargs): instance. order. state = REFUNDING instance. order. save () # here, order is a foreign key of refundform
Of course, more details can be written here, such as canceling and changing the status of a refund ticket.
Observer is a very practical design model, and Django also supports user-defined signals.