Django中的信号signals
什么是信号?
jango的信号机制就是事件驱动模型,一个事件可以被多个函数注册,当一个动作行为触发了这个事件后,这个事件所对应的函数便执行相应的操作;
内置信号;
django 内部有些定义好的signal供我们使用:
模型相关:
pre_save 对象save前触发
post_save 对象save后触发
pre_delete 对象delete前触发
post_delete 对象delete后触发
m2m_changed ManyToManyField 字段更新后触发
请求相关:
request_started 一个request请求前触发
request_finished request请求后触发
应用场景
适用于:当修改model的时候,需要执行一些与当前app无关额外的操作,比如逻辑中包含第三方的库;执行的多个行为且后续仍可能添加操作等;
不适用:修改当前app中的某个model,这种场景建议放到save函数中执行;
from django.core.signals import request_finished
from django.core.signals import request_started
from django.core.signals import got_request_exception
from django.db.models.signals import class_prepared
from django.db.models.signals import pre_init, post_init
from django.db.models.signals import pre_save, post_save
from django.db.models.signals import pre_delete, post_delete
from django.db.models.signals import m2m_changed
from django.db.models.signals import pre_migrate, post_migrate
from django.test.signals import setting_changed
from django.test.signals import template_rendered
from django.db.backends.signals import connection_created
信号的实现
首先在app中注册对应的信号名称,使信号生效
然后看案例:
from django.db.models.signals import pre_save, post_save
def callback(sender, **kwargs):
print("xxoo_callback")
print(sender, kwargs)
post_save.connect(callback)
from django.dispatch import receiver
@receiver(post_save)
def callback1(sender, **kwargs):
print("xxoo_callback1111111")
print(sender, kwargs)