is_dirty and dict of changed values

 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

  1. Update only selected model fields by jcrocholl 5 years, 6 months ago
  2. create or update, then get, model instances from JSON/py dict by anentropic 1 year, 5 months ago
  3. update_or_create by abhin4v 4 years, 7 months ago
  4. Prefetch id for Postgresql backend by bretth 1 year, 1 month ago
  5. Binding signals to abstract models by andreterra 1 year ago

Comments

(Forgotten your password?)