Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Detecting changes of a set of fields when a model is saved

The problem

I have a field in my model that requires some calculation. I want to perform these calculations when the model is saved. However, because it is resource intensive, I want to only perform these calculations when certain fields have changed.

Initial thought

Keep the hash of the 3 fields as a different field in the model. On save, hash the three fields and, if equal to the the one currently saved in the model, continue on saving the instance without further work. Otherwise, perform calculations, save the results of the calculation and save new hash.

My questions:

  1. Is this the best option? If not, please share what would be better and why.

  2. If there isn't a better way: Which kind of hash should I use? And why?

  3. Which kind of Django model field type should I use to save the hash?

like image 540
Belmin Fernandez Avatar asked Nov 29 '10 19:11

Belmin Fernandez


1 Answers

I am submitting the implementation of my initial thought as an answer to be critiqued by others:

models.py

from hashlib import md5

class Stop(models.Model):
    line = models.CharField(max_length=12)
    street = models.CharField(max_length=32, choices=STREET_CHOICES)
    order = models.PositiveIntegerField(blank=True, null=True)
    location_hash = models.CharField(max_length=32, null=True)

    def save(self):
        location_hash = md5('%s@%s' % (self.line, self.street))
        if self.location_hash != location_hash:
            self.order = calculate_order(line=self.line, street=self.street)
            self.location_hash = location_hash
        super(Stop, self).save()

If anyone has any suggestions, comments or concerns; please share!

like image 84
Belmin Fernandez Avatar answered Sep 27 '22 20:09

Belmin Fernandez