blob: 709fdc602b8a63cc24a1b396c973c453f0a64d70 [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)
Tony Mackb0d97422013-06-10 09:57:45 -04009 enacted = models.DateTimeField(null=True, default=None)
Siobhan Tully4bc09f22013-04-10 21:15:21 -040010
11 class Meta:
12 abstract = True
13 app_label = "core"
14
Scott Baker13acdd62013-05-08 17:42:56 -070015 def __init__(self, *args, **kwargs):
16 super(PlCoreBase, self).__init__(*args, **kwargs)
17 self.__initial = self._dict
18
19 @property
Siobhan Tully73291342013-05-10 10:50:08 -040020 def diff(self):
21 d1 = self.__initial
22 d2 = self._dict
23 diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
24 return dict(diffs)
25
26 @property
27 def has_changed(self):
28 return bool(self.diff)
29
30 @property
31 def changed_fields(self):
32 return self.diff.keys()
33
34 def get_field_diff(self, field_name):
35 return self.diff.get(field_name, None)
36
37 def save(self, *args, **kwargs):
38 super(PlCoreBase, self).save(*args, **kwargs)
Scott Baker13acdd62013-05-08 17:42:56 -070039 self.__initial = self._dict
40
41 @property
Siobhan Tully73291342013-05-10 10:50:08 -040042 def _dict(self):
43 return model_to_dict(self, fields=[field.name for field in
Scott Baker13acdd62013-05-08 17:42:56 -070044 self._meta.fields])
45
Siobhan Tully4bc09f22013-04-10 21:15:21 -040046
47