24

I have a database model that is being updated based on changes in remote data (via an HTML scraper).

I want to maintain a field called changed - a timestamp denoting when the last time that model's values changed from what they were previously (note that this is different from auto_now as these fields are updated every time a model's save method is called).

Here is my question:

In a model's save method, is there a straightforward way to detect if a model instance's current values are different from the values in the database? Or, are there any alternative methods to easily maintain a changed timestamp?

1

5 Answers 5

36

If you save your instance through a form, you can check form.has_changed().

Sign up to request clarification or add additional context in comments.

1 Comment

And if you want to know which field(s) changed: form.changed_data
13

http://code.activestate.com/pypm/django-dirtyfields/

Tracks dirty/changed fields on a django model instance.

Comments

3

Sounds to me like what you want is Signals: http://docs.djangoproject.com/en/1.2/topics/signals/

You could use a post_save signal to update a related field in another model to store the previous value. Then on the next go-round you'd have something to compare.

1 Comment

3

You might try computing a checksum of the record values when you save them. Then when you read it later, recompute the checksum and see if it has changed. Perhaps the crc32 function in the Python zlib standard module. (I'm not sure what kind of performance this would have. So you may want to investigate that.)

3 Comments

Interesting. Is there an easy way to look at the entirety of an object's data so that it can be easily checksummed? And is it possible that two identical (having the same field values) instances of an object have different "data" (the input read by our checksum function).
1. The method I would use is to simply get all the field data, convert each to a string, concatenate it all, and checksum that. 2. It is theoretically possible to have two instances with different data come up with the same checksum, but it is very unlikely. If you are really concerned about that, you can use a cryptographic hash function in which that be all but impossible; but it would be more expensive to calculate.
@dappawit you should also consider ordering of concatenation which could cause issues with your logic. hash("a=1b=2c=3") != hash("a=1c=3b=2"). Regardless, another good approach.
0

This library has tracks FK lookups.

https://github.com/mmilkin/django_dirty_bits

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.