How to tell if a fields was modified

3 views
Skip to first unread message

Matias

unread,
Jul 24, 2009, 12:37:08 PM7/24/09
to django...@googlegroups.com
Hi,

How can I tell which model fields have been modified (this is, the
difference between the Model instance and the data originally retrieved
from the database) from inside the model's save() method?


Any idea?

Thanks a lot!

Randy Barlow

unread,
Jul 24, 2009, 12:45:17 PM7/24/09
to django...@googlegroups.com
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Matias declared:


> How can I tell which model fields have been modified (this is, the
> difference between the Model instance and the data originally retrieved
> from the database) from inside the model's save() method?

You can always retrieve the model by it's primary key from the db, and
then compare self to it. Something like:

def save(stuff_and_junk):
existing_instance = self.__class__.objects.get(id=self.id)
if existing_instance.attribute != self.attribute:
print 'Holy Crap!'
super(self.__class__, self).save(stuff_and_junk)

- --
Randy Barlow
Software Developer
The American Research Institute
http://americanri.com
919.228.4971
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkpp5RwACgkQw3vjPfF7QfWmUgCePIAaqGQ6XFWtdEKa86V98Xij
bnUAnjn758cASuyP8wCPkbOEV6Oa3ZGQ
=NqNX
-----END PGP SIGNATURE-----

Tim Chase

unread,
Jul 24, 2009, 1:20:43 PM7/24/09
to django...@googlegroups.com
>> How can I tell which model fields have been modified (this is, the
>> difference between the Model instance and the data originally retrieved
>> from the database) from inside the model's save() method?
>
> You can always retrieve the model by it's primary key from the db, and
> then compare self to it. Something like:
>
> def save(stuff_and_junk):
> existing_instance = self.__class__.objects.get(id=self.id)
> if existing_instance.attribute != self.attribute:
> print 'Holy Crap!'
> super(self.__class__, self).save(stuff_and_junk)

Remembering, of course, that get() can throw an exception if
you're creating a new object...

-tim


ankit rai

unread,
Jul 24, 2009, 1:24:59 PM7/24/09
to django...@googlegroups.com

use clean method and use self.instance.fieldname to know previous value and then compare with the new value.
Reply all
Reply to author
Forward
0 new messages