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

  • 相关阅读:
    背景图片填充问题
    a:hover 等伪类选择器
    jQuery中animate()方法用法实例
    响应式框架Bootstrap
    HTTP入门
    jQuery选择器
    httplib urllib urllib2 pycurl 比较
    校招
    JAVA描述的简单ORM框架
    Roman to Integer
  • 原文地址:https://www.cnblogs.com/feifeifeisir/p/13744385.html
Copyright © 2011-2022 走看看