I got fed up with manually checking if a field has changed in the save method of Django models so I quickly wrote this snippet to generalize it:
def has_changed(instance, field):
if not instance.pk:
return False
old_value = instance.__class__._default_manager.\
filter(pk=instance.pk).values(field).get()[field]
return not getattr(instance, field) == old_value
Here’s how could be used:
class Sneetch(models.Model):
has_star = models.BooleanField(default=False)
succumbs_to_peer_pressure = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if has_changed(self, 'has_star'):
self.succumbs_to_peer_pressure = True
super(Sneetch, self).save(*args, **kwargs)
Let me know if you improve it…


