How to detect changes in a model's fields before save() ?

4,703 views
Skip to first unread message

zhango

unread,
Oct 10, 2008, 8:59:36 PM10/10/08
to Django users
I'm overriding a model's save() method, and I want to detect changes
in values for some of the model's fields (i.e. differences between the
unsaved instance's values for some fields, and the values for those
same fields currently in the database and about to be overwritten).
Is it possible to do this, and if so, how?

Thanks in advance for any help!

Donn

unread,
Oct 11, 2008, 12:03:37 PM10/11/08
to django...@googlegroups.com
Sounds like you should be doing something in the form's clean() function. You
can compare what's in the cleaned_data to what's in the model and then move
from there.

\d

bruno desthuilliers

unread,
Oct 12, 2008, 4:06:55 PM10/12/08
to Django users
class Yadda(models.Model):
blah = models.CharField(max_length=32)

def __unicode__(self):
return u"%s" % self.blah

def __init__(self, *args, **kw):
print "yadda __init__", args, kw
super(Yadda, self).__init__(*args, **kw)
self._old_blah = self.blah

def save(self, **kw):
print "yadda save"
if self.blah != self._old_blah:
print "blah changed - was : %s - now : %s" %
(self._old_blah, self.blah)
super(Yadda, self).save(**kw)


bruno desthuilliers

unread,
Oct 12, 2008, 4:08:08 PM10/12/08
to Django users
And what if you didn't use a form to alter the model instance ?

zhango

unread,
Oct 13, 2008, 9:33:56 AM10/13/08
to Django users
Thanks Donn, for the suggestion, but I'm actually not getting the data
via a form, I'm using the ORM in a long-running script.

I've figured out one way to do this: in overriding the save() method,
the self instance passed in has the new values; simply use self.id to
retrieve the prior version, compared its values with those of the
still-unsaved self instance. Seems to work just fine.

zhango

unread,
Oct 13, 2008, 9:35:29 AM10/13/08
to Django users
Bruno - yes, your solution is even better as it avoids a database
lookup. Thank you!


On Oct 12, 4:06 pm, bruno desthuilliers

bruno desthuilliers

unread,
Oct 13, 2008, 10:45:47 AM10/13/08
to Django users
On 13 oct, 15:35, zhango <alex.zhang...@gmail.com> wrote:
> Bruno - yes, your solution is even better as it avoids a database
> lookup.

Yeps, that's mostly the point. But beware : it's not *fully* tested.
IOW : it _should_ work but you'd better test it more carefully than I
did !-)

Reply all
Reply to author
Forward
0 new messages