compare old and new model field value

1,151 views
Skip to first unread message

Tim

unread,
Nov 10, 2008, 2:03:16 PM11/10/08
to Django users
Basically, I want to be able to do something if the value of a field
changes in a model.

c = Category.objects.get(pk=1)
c.name = "New Name"
c.save()

At any point (when the model is saved, when the value is set, etc.) is
it possible to compare the old and new value? The first thought that
popped into my head was something like this. I know this exact code
isn't possible, it's just an example of what I'm trying to do.

class Category(models.Models):

def save(self):
if self.name.old_value != self.name.value:
do something fun here
super(Category, self).save()

If something like this isn't built in to Django, I was thinking of
writing a custom field and overwriting __set__() to store the old
value somewhere, since that seems to be the only place that would have
access to the new and old value.

Any thoughts on whether that's the best method?

Alex Koshelev

unread,
Nov 11, 2008, 6:00:08 AM11/11/08
to django...@googlegroups.com
Why not simple fetch `old version` of object from database and compare its fields. For example:

def save(self, *args, **kwargs):
   if self._get_pk_val():
       old = self.__class__.objects.get(pk=self._get_pk_val()
       for field in self.__class__._meta.fields:
           old_value = field._get_val_from_obj(old)
           current_value = field._get_val_from_obj(self)

           if old_value != current_value:
                #do something fun here

    super(self.__class__, self).save(*args, **kwargs)

Rock

unread,
Nov 11, 2008, 10:35:22 AM11/11/08
to Django users
Take a look at http://code.google.com/p/django-reversion/ which may be
more than what you need, but certainly fills the bill for your general
use case.
Reply all
Reply to author
Forward
0 new messages