Login

Compare two instances of the same model

Author:
IzzaddinRuhulessin
Posted:
November 30, 2010
Language:
Python
Version:
1.2
Tags:
models comparison
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

  1. really_equals by zeeg 7 years, 10 months ago
  2. How to compare two versions? by RafRaf 1 year, 4 months ago
  3. Custom collectstatic that uses etag and md5 digests to determine whether files on S3 have changed by millarm 2 years, 1 month ago
  4. Run Django as a FastCGI authorizer by cme 6 years, 5 months ago
  5. db_dump.py - for dumpping and loading data from database by limodou 8 years, 1 month ago

Comments

Please login first before commenting.