blob: ed7c3ffcbefb6bcfd3ead3b2b5ad1f88541634ba [file] [log] [blame]
Siobhan Tully4bc09f22013-04-10 21:15:21 -04001import os
2from django.db import models
Scott Baker13acdd62013-05-08 17:42:56 -07003from django.forms.models import model_to_dict
Siobhan Tully4bc09f22013-04-10 21:15:21 -04004
5class PlCoreBase(models.Model):
6
7 created = models.DateTimeField(auto_now_add=True)
8 updated = models.DateTimeField(auto_now=True)
9
10 class Meta:
11 abstract = True
12 app_label = "core"
13
Scott Baker13acdd62013-05-08 17:42:56 -070014 def __init__(self, *args, **kwargs):
15 super(PlCoreBase, self).__init__(*args, **kwargs)
16 self.__initial = self._dict
17
18 @property
Siobhan Tully73291342013-05-10 10:50:08 -040019 def diff(self):
20 d1 = self.__initial
21 d2 = self._dict
22 diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
23 return dict(diffs)
24
25 @property
26 def has_changed(self):
27 return bool(self.diff)
28
29 @property
30 def changed_fields(self):
31 return self.diff.keys()
32
33 def get_field_diff(self, field_name):
34 return self.diff.get(field_name, None)
35
36 def save(self, *args, **kwargs):
37 super(PlCoreBase, self).save(*args, **kwargs)
Scott Baker13acdd62013-05-08 17:42:56 -070038 self.__initial = self._dict
39
40 @property
Siobhan Tully73291342013-05-10 10:50:08 -040041 def _dict(self):
42 return model_to_dict(self, fields=[field.name for field in
Scott Baker13acdd62013-05-08 17:42:56 -070043 self._meta.fields])
44
Siobhan Tully4bc09f22013-04-10 21:15:21 -040045
46