django - How to customise Model save method when a specified field is changed
<p>I have a model, let's save A, the definition is as below:</p>

<pre><code>class A(models.Model):
   name = models.CharField('name', max_length=10)
   enabled = models.BooleanField('enabled', default=False)
   field1 = models.CharField('field1', max_length=10)
   field2 = models.CharField('field2', max_length=10)
   field3 = models.CharField('field3', max_length=10)
   parent = models.ForeignKey('self', null=True, blank=True) # hierarchy
</code></pre>

<p>and some object instances of this model, a, b, c, d. the hierarchy is represented by the parent field.</p>

<pre><code>a 
|-- b
    |-- c
    |-- d
</code></pre>

<p>So, what I need to do is, when <code>b.enabled</code> change from <code>False</code> to <code>True</code>, or vice versa, I need to update <code>c.enabled</code> and <code>d.enabled</code> to value: <code>b.enabled</code>.</p>

<p>That's say, I need to broadcast the change to the children instances when the parent's <code>enabled</code> field was changed.</p>

<p>For performance consideration, I only need to broadcast the changes when <code>enabled</code> field is really changed. And don't want to always update the child instance whenever the parent is save, e.g. only updating field1 or field2.</p>

<p>So, do anyone knows, what is the best way to implement this logic? Thanks in advance.</p>

<p>In short â no. But you can do it manually overloading the save method.</p>

<pre><code>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, **kw)
</code></pre>

python django save