[Fixed]-Override model save method to automatically store previous values of updated fields

1👍

You could retrieve the old record from the database before saving:

recording_time = models.DateTimeField(auto_now=True)
previous_value = models.FloatField(null=True, default=None)
previous_recording_time = models.DateTimeField(null=True, default=None)

def save(self, force_insert=False, force_update=False, using=None,
         update_fields=None):
    try:  
        obj = Observation.objects.get(pk=self.pk)  
        # this is the record of this instance before editing
    except Observation.DoesNotExist:  # self.pk==None: this is a new Observation
        pass
    else:  #  this is indeed an update
        self.previous_value = obj.value
        previous_db_recording_time = obj.db_recording_time
    super(Observation, self).save(force_insert=force_insert, force_update=force_update, using=using,
         update_fields=update_fields)

Now, nobody should ever have to manually set recording_time, previous_value, or previous_recording_time. So you can exclude those fields from the ModelForm that you use in Observation‘s Admin class.

0👍

As I suggested in comments, you could add a foreign key to self in Observation model which refers to the observation taken earlier and then you don’t need to duplicate these fields e.g. previous_value, previous_db_recording_time.

class Observation(models.Model):
    ...
    prev_observation = models.ForeignKey('self', null=True)

    # you can also add a `is_recent` field to this model so you set it to True when its created
    is_recent = models.BooleanField(default=True)

So let’s say you added 7 observations in a week [o1, o2, o3, o4, o5, o6, o7] so for all these 7 is_recentt will be True.

And, you can get these observations as follows:

Observation.objects.filter(probe=chosenprobe, 
                           obstime__gte=start, obstime__lte=end,
                           is_recent=True)

# [o1, o2, o3, o4, o5, o6, o7]

Now, you corrected o1, o3 and o6 with o8, o9 and o10 so at this time you can set is_recent for o1, o3 and o6 to False.

And, then running the above query again will give you updated (recent) observations:

# [o2, o4, o5, o7, o8, o9, o10]
👤AKS

Leave a comment