Needed a function to check if any field in an instance has changed. If so update a datetime field to now to keep track of changes. This function is an override of the save function in the model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | def save(self, latest_update_at):
changed = False
# if inserting don't add the latest update at
if self.id is None:
super(Match, self).save()
# otherwise check if any fields have changed
for field in self._meta.get_all_field_names():
if changed:
continue
old_value = getattr(self.__class__._default_manager.get(id=self.id), field)
new_value = getattr(self, field)
if new_value != old_value:
changed = True
if changed:
self.latest_update_at = datetime.now()
super(Match, self).save()
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
I think save() of the superclass is called twice when inserting (probably not what you want).
Also, the old object is retrieved from the database for every field. You probably want something like (untested):
Lastly, in most cases the
auto_now
property ofDateTimeField
should suffice.#
Please login first before commenting.