每次变量变化时,在Django模型中触发一个函数

时间:2017-07-13 05:08:59

标签: python django django-models

我正在研究Django模型,我想在每次变量变化时触发一个函数。这是我的模特:

class Cv(models.Model):
    name = models.CharField(max_length=100)
    position = models.ForeignKey(
        OpenPosition,
        on_delete=models.CASCADE,
        null=True,
    )
    team = models.ForeignKey(
        Team,
        on_delete=models.CASCADE,
        null=True
    )
    leader = models.ForeignKey(Leader, on_delete=models.CASCADE)

    email = models.EmailField(
        max_length=100,
        null=False,
        validators=[EmailValidator()],
        blank=True
    )
    email_sent_status = models.BooleanField(default=False)
    phone = models.CharField(
        validators=[
            RegexValidator(
                regex=r'^(0\d{9,11})$',
                message='''
                Phone number must be started with 0 and has 10-12 digits
                '''
            )],
        blank=True,
        null=True,
        max_length=20,
    )
    link = models.CharField(
        max_length=150,
        validators=[URLValidator()],
    )
    source = models.ForeignKey(CvSource, on_delete=models.CASCADE)
    cv_status = models.CharField(
        max_length=10,
        choices=STATUS,
        default='u',
    )
    schedule = models.DateTimeField(blank=True, null=True)
    schedule_confirm = models.BooleanField(default=False)
    interview_status = models.CharField(
        max_length=10,
        choices=FULL_STATUS,
       default='u',
   )
   test_status = models.CharField(
       max_length=10,
       choices=STATUS,
       default='u',
    )
    test_comment = models.TextField(max_length=200, blank=True)
    decision_status = models.CharField(
        max_length=10,
        choices=FULL_STATUS,
        default='u',
    )
    offer_status = models.CharField(
        max_length=10,
        choices=OFFER_STATUS,
        default='u,'
    )
    internal_comment = models.TextField(max_length=200, blank=True)
    created_at = models.DateTimeField(
        editable=False,
        null=True,
    )
    updated_by = models.CharField(max_length=30, editable=False, null=True)

目前我使用Django: When saving, how can you check if a field has changed?中提到的方法,但是有很多变量,这个过程变得重复:

def __init__(self, *args, **kwargs):
    super(Cv, self).__init__(*args, **kwargs)
    #override original fields' values with current values
    self.__original_schedule = self.schedule
    self.__original_schedule_confirm = self.schedule_confirm
    self.__original_name = self.name
    self.__original_position = self.position
    self.__original_team = self.team
    self.__original_leader = self.leader
    self.__original_email = self.email
    self.__original_email_sent_status = self.email_sent_status
    self.__original_phone = self.phone
    #etc

def save(self, *args, **kwargs):
    if self.__original_schedule != self.schedule: 
        #do something etc

我想找到一种优化此过程的方法。我在某处读过你可以使用@property跟踪变量'变化,我想知道我是否可以在我的模型中使用这种方法。如果没有,还有其他方法可以改进我的方法。

1 个答案:

答案 0 :(得分:2)

为什么不 django信号see docs here

每次保存模型对象时都会触发

post_save 信号。

工作示例:

在你的models.py中添加..

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Cv)
def hear_signal(sender , instance , **kwargs):
    if kwargs.get('created'):
        return # if a new model object is created then return. You need to distinguish between a new object created and the one that just got updated.

    #Do whatever you want. 
    #Your trigger function content.
    #Parameter "instance" will have access to all the attributes of the model being saved. To quote from docs : It's "The actual instance being saved."        

    return

感谢。希望这会有所帮助。