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>The best way to do this is using django signals <a href="https://docs.djangoproject.com/es/1.10/ref/signals/" rel="nofollow">https://docs.djangoproject.com/es/1.10/ref/signals/</a></p>

<p>You will call the method change_status when your model call the method <code>save()</code></p>

<pre><code>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
</code></pre>

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

python django save