- Author:
- jaredthane
- Posted:
- August 13, 2009
- Language:
- Python
- Version:
- 1.1
- Score:
- 2 (after 2 ratings)
When you call model.changed_columns() you get a dict of all changed values. When you call model.is_dirty() you get boolean whether or not the object has been changed since last save
Based on an answer here:http://stackoverflow.com/questions/110803/dirty-fields-in-django but fixed and added is_dirty
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class DiffingMixin(object):
def __init__(self, *args, **kwargs):
super(DiffingMixin, self).__init__(*args, **kwargs)
self._original_state = dict(self.__dict__)
def save(self, *args, **kwargs):
state = dict(self.__dict__)
del state['_original_state']
self._original_state = state
super(DiffingMixin, self).save()
def is_dirty(self):
missing = object()
result = {}
for key, value in self._original_state.iteritems():
if value != self.__dict__.get(key, missing):
return True
return False
def changed_columns(self):
missing = object()
result = {}
for key, value in self._original_state.iteritems():
if value != self.__dict__.get(key, missing):
result[key] = {'old':value, 'new':self.__dict__.get(key, missing)}
return result
|
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
Please login first before commenting.