Login

is_dirty and dict of changed values

Author:
jaredthane
Posted:
August 13, 2009
Language:
Python
Version:
1.1
Tags:
django models save dirty
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

  1. BigIntegerField and BigAutoField by fnl 6 years, 7 months ago
  2. Prefetch id for Postgresql backend by bretth 3 years, 3 months ago
  3. Quickly check templates while sketching them out by amr-mostafa 8 years, 3 months ago
  4. HTML to POST dict converter by guettli 7 years, 8 months ago
  5. Custom model field to store dict object in database by rudyryk 5 years, 3 months ago

Comments

Please login first before commenting.