blob: b64df5fc74bd163f672aeeeb7808b57cb6076960 [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
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -04004# This is a no-op if observer_disabled is set to 1 in the config file
5from observer import *
Siobhan Tully4bc09f22013-04-10 21:15:21 -04006
7class PlCoreBase(models.Model):
8
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -04009 created = models.DateTimeField(auto_now_add=True)
10 updated = models.DateTimeField(auto_now=True)
11 enacted = models.DateTimeField(null=True, default=None)
Siobhan Tully4bc09f22013-04-10 21:15:21 -040012
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040013 class Meta:
14 abstract = True
15 app_label = "core"
Siobhan Tully4bc09f22013-04-10 21:15:21 -040016
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040017 def __init__(self, *args, **kwargs):
18 super(PlCoreBase, self).__init__(*args, **kwargs)
19 self.__initial = self._dict
Scott Baker13acdd62013-05-08 17:42:56 -070020
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040021 @property
22 def diff(self):
23 d1 = self.__initial
24 d2 = self._dict
25 diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
26 return dict(diffs)
Siobhan Tully73291342013-05-10 10:50:08 -040027
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040028 @property
29 def has_changed(self):
30 return bool(self.diff)
Siobhan Tully73291342013-05-10 10:50:08 -040031
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040032 @property
33 def changed_fields(self):
34 return self.diff.keys()
Siobhan Tully73291342013-05-10 10:50:08 -040035
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040036 def get_field_diff(self, field_name):
37 return self.diff.get(field_name, None)
Siobhan Tully73291342013-05-10 10:50:08 -040038
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040039 def delete(self, *args, **kwds):
40 super(PlCoreBase, self).delete(*args, **kwds)
Sapan Bhatiadbaf1932013-09-03 11:28:52 -040041
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040042 # This is a no-op if observer_disabled is set
43 notify_observer(model=self, delete=True)
Sapan Bhatiadbaf1932013-09-03 11:28:52 -040044
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040045 def save(self, *args, **kwargs):
46 super(PlCoreBase, self).save(*args, **kwargs)
47
48 # This is a no-op if observer_disabled is set
49 notify_observer()
Sapan Bhatia66f4e612013-07-02 12:12:38 -040050
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040051 self.__initial = self._dict
Scott Baker13acdd62013-05-08 17:42:56 -070052
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040053 @property
54 def _dict(self):
55 return model_to_dict(self, fields=[field.name for field in
56 self._meta.fields])
Scott Baker13acdd62013-05-08 17:42:56 -070057
Siobhan Tully4bc09f22013-04-10 21:15:21 -040058
59