Brendan
Brendan

Reputation: 300

Is there a way of triggering an action when a specific field is changed in Django models

I am looking for a way to trigger an action whenever a specific field on a model is changed, regardless of where it is changed.

To add some context, I have been experiencing an elusive bug, where occasionally a date field is being set to the 13th of January 2020, I have absolutely no idea where in the codebase this is happening, it is also happening seldom enough that I have not been able to pick up any pattern as to what could be causing it.

What I would like to do is trigger some kind of an alert whenever this field is changed to the 13th of Jan 2020, so I can attempt to isolate what is causing it.

Upvotes: 0

Views: 2011

Answers (2)

Sami
Sami

Reputation: 381

You can use post_save and post_init signal, to know when the field of a Model is changed. post_save post_init It will trigger alert whenever an object is updated and has 13 Jan 2020 as date.

from django.db.models.signals import post_save, post_init
import datetime

@receiver(post_init, sender=YourModel)
def remember_previous_date(sender, instance, **kwargs):
    instance.previous_date = instance.your_date_field

@receiver(post_save, sender=YourModel)
def create_user_api_key(sender, instance, created, **kwargs):
    if not created:
        is_date_updated = instance.previous_date != instance.your_date_field
        day = datetime.date(2020, 1, 13)
        if instance.your_date_field == day and is_date_updated:
            trigger_your_alert()

Upvotes: 3

RaideR
RaideR

Reputation: 937

Not sure if it's the best method, but you could overwrite the model's save method.

    def save(self, *args, **kwargs):
        if self.pk is not None:
            old_instance = YourModel.objects.get(pk=self.pk)
            if old_instance.your_date_field != self.your_date_field:
                trigger_your_alert()

        super().save(*args, **kwargs)

Upvotes: 1

Related Questions