- Author:
- IzzaddinRuhulessin
- Posted:
- November 30, 2010
- Language:
- Python
- Version:
- 1.2
- Score:
- 1 (after 1 ratings)
This compares two objects (of the same model) and returns a tuple containing dictionaries with the changed attributes. Note that ALL attributes are run through comparison, so if you are modifying non-field attributes at runtime, these will also be included.
Excluded keys is a tuple containing the names if attributes you do not want to include in the comparison loop (i.e. attributes which changes are irrelevant).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class MyModel(models.Model):
#Things
def compare(self, obj):
excluded_keys = 'created', '_state', 'timestamp', 'user', 'uid', 'changed' #Example. Modify to your likings.
return self._compare(self, obj, excluded_keys)
def _compare(self, obj1, obj2, excluded_keys):
d1, d2 = obj1.__dict__, obj2.__dict__
old, new = {}, {}
for k,v in d1.items():
if k in excluded_keys:
continue
try:
if v != d2[k]:
old.update({k: v})
new.update({k: d2[k]})
except KeyError:
old.update({k: v})
return old, new
|
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, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.