[Answered ]-Django – How to customise Model save method when a specified field is changed

1πŸ‘

βœ…

The best way to do this is using django signals https://docs.djangoproject.com/es/1.10/ref/signals/

You will call the method change_status when your model call the method save()

from django.db.models.signals import pre_save

def change_status(sender, instance, **kwargs):
    # instance object is the model that you have called the method save
    a = A.objects.get(id=instance.id) # or B or C model
    if instance.enable:
        a.enable = False
        # my code.....

pre_save.connect(change_status, sender=A) 
# sender is the model that will be called every time you call the method save

And That’s it
Remember that the object instance is your model before be changed, so
if you have a.enable=True and call the method save() in change_status signal you can make a query without this change of a.enable=True
intance.enable >> True, a.enable >> False because a is not saved yet.

1πŸ‘

In short β€” no. But you can do it manually overloading the save method.

class B(models.Model):

    ...

    def save(self, *args, **kwargs):
        if self.pk is not None:
            original = B.objects.get(pk=self.pk)
            if original.enabled != self.enabled:
                C.enabled = self.enabled
                C.save()
                D.enabled = self.enabled
                D.save()
        super(B, self).save(*args, **kwargs)

Β 

Leave a comment