Compare two instances of the same model

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

Comments

(Forgotten your password?)