django: is it possible to keep a model field updated with a model method?
<p>So basically I have a model Equipment that has foreign key calibration. I would like to have a field in Equipment as 'latest_calibrated_date' which get the 'cal_date' from the newest created calibration. Here is what I have now:</p>

<pre><code>def latest_calibration_date(self):
        return Calibration.objects.filter(cal_asset__id = self.id).order_by('-id')[0].cal_date
</code></pre>

<p>However, for the purpose of some other apps, I would like to make this not a method but a field. So I am thinking about use a latest_calibration_date = models.DateField() and update it every time a new Calibration is added. How could I do this?</p>

<p>As <em>Daniel Roseman</em> pointed out, you can override <code>save</code> method on <code>Calibration</code> model. For example:</p>

<pre><code>class Calibration(model.Model):
    # your fields

    def save(self, *args, **kwargs):
        super(Calibration, self).save(*args, **kwargs)

        # update latest calibration date 
</code></pre>

<p>You can store your parameter in many ways, for example by creating <code>Parameter</code> model for storing your variables.</p>

<pre><code>class Parameter(models.Model):
    key = models.CharField(max_length=255, unique=True)
    value = models.IntegerField()
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.key
</code></pre>

<p>and then again in <code>save</code>:</p>

<pre><code>import time

p = Parameter.objects.get(key='LATEST_CALIBRATION_DATE')
p.value = time.time() # save in UNIX timestamp
p.save()
</code></pre>

<p>or whatever format you like.</p>

python django