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.
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.
Is this the best option? If not, please share what would be better and why.
If there isn't a better way: Which kind of hash should I use? And why?
Which kind of Django model field type should I use to save the hash?
I am submitting the implementation of my initial thought as an answer to be critiqued by others:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With