Update timestamp If any instance field has changed

 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

  1. Another means of updating a subset of a model's fields by insin 5 years, 6 months ago
  2. "Approved" field with timestamp by miracle2k 5 years, 10 months ago
  3. Update only selected model fields by jcrocholl 5 years, 6 months ago
  4. Check If a Field Has Changed by zmsmith 3 years ago
  5. UTC DateTime field by ludo 5 years, 9 months ago

Comments

arthur (on August 5, 2011):

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):

old_object = self.__class__._default_manager.get(id=self.id)
changed = any(getattr(self, field) != getattr(old_object
              for field in self._meta.get_all_field_names())

Lastly, in most cases the auto_now property of DateTimeField should suffice.

#

(Forgotten your password?)