Django signals 监控模型对象字段值的变化
举一个例子:当学生名字发生改变之后发布一条公告。
from django.db.models import signals from django.dispatch import receiver from students.models import Student from .models import Announcement @receiver(signals.post_init, sender=Student) def welcome_student(instance, **kwargs): instance.__original_name = instance.name @receiver(signals.post_save, sender=Student) def welcome_student(instance, created, **kwargs): if not created and instance.__original_name != instance.name: Announcement.objects.create(content= 'Student %s has renamed to %s' % (instance.__original_name, instance.name))
简单的说就是在该模型广播 post_init
信号的时候,在模型对象中缓存当前的字段值;在模型广播 post_save
(或 pre_save
)的时候,比较该模型对象的当前的字段值与缓存的字段值,如果不相同则认为该字段值发生了变化。