Skip to content

Instantly share code, notes, and snippets.

@k1000
Created August 5, 2011 13:55
Show Gist options
  • Save k1000/1127582 to your computer and use it in GitHub Desktop.
Save k1000/1127582 to your computer and use it in GitHub Desktop.
TrackStateMixin to track updated fields in django model
# -*- coding: utf-8 -*-
from django.db.models.signals import post_save
#https://github.com/citylive/django-states2
#inspired on http://stackoverflow.com/questions/110803/dirty-fields-in-django
class TrackStateMixin(object):
def __init__(self, *args, **kwargs):
super(TrackStateMixin, self).__init__(*args, **kwargs)
self._original_state = self._as_dict()
def _reset_state(self, *args, **kwargs):
self._original_state = self._as_dict()
def _as_dict(self):
return dict([(f.attname, getattr(self, f.attname)) for f in self._meta.local_fields])
def get_updated_fields(self):
new_state = self._as_dict()
return dict([(key, [ value, new_state[key] ]) for key, value in self._original_state.iteritems() if value != new_state[key]])
def update_callback(self):
def save(self, *args, **kwargs):
super(TrackStateMixin, self).save(*args, **kwargs)
updated_fields = self.get_updated_fields()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment