举一个例子:当学生名字发生改变之后发布一条公告。

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 )的时候,比较该模型对象的当前的字段值与缓存的字段值,如果不相同则认为该字段值发生了变化。 

相关文章:

  • 2021-07-29
  • 2022-12-23
  • 2022-12-23
  • 2021-09-21
  • 2022-01-14
  • 2021-06-12
  • 2021-07-04
猜你喜欢
  • 2022-12-23
  • 2018-11-19
  • 2022-12-23
  • 2021-07-16
  • 2021-05-22
  • 2022-12-23
相关资源
相似解决方案