blob: 921b89b18eef0056e7e605f303d2f4d0d74e0286 [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 Bhatiabd028412013-09-03 11:53:18 -04004from observer.event_manager import EventSender
Sapan Bhatia66f4e612013-07-02 12:12:38 -04005
Siobhan Tully4bc09f22013-04-10 21:15:21 -04006
7class PlCoreBase(models.Model):
8
Sapan Bhatia322edfa2013-10-02 10:04:06 -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 Bhatia322edfa2013-10-02 10:04:06 -040013 class Meta:
14 abstract = True
15 app_label = "core"
Siobhan Tully4bc09f22013-04-10 21:15:21 -040016
Sapan Bhatia322edfa2013-10-02 10:04:06 -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 Bhatia322edfa2013-10-02 10:04:06 -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 Bhatia322edfa2013-10-02 10:04:06 -040028 @property
29 def has_changed(self):
30 return bool(self.diff)
Siobhan Tully73291342013-05-10 10:50:08 -040031
Sapan Bhatia322edfa2013-10-02 10:04:06 -040032 @property
33 def changed_fields(self):
34 return self.diff.keys()
Siobhan Tully73291342013-05-10 10:50:08 -040035
Sapan Bhatia322edfa2013-10-02 10:04:06 -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 Bhatia322edfa2013-10-02 10:04:06 -040039 def delete(self, *args, **kwds):
40 super(PlCoreBase, self).delete(*args, **kwds)
Sapan Bhatiadbaf1932013-09-03 11:28:52 -040041
Sapan Bhatia322edfa2013-10-02 10:04:06 -040042 try:
43 EventSender().fire({'delete_flag':True,'model':self.__name__})
44 except:
45 # Investigate later.
46 pass
Sapan Bhatiadbaf1932013-09-03 11:28:52 -040047
Sapan Bhatia66f4e612013-07-02 12:12:38 -040048
Sapan Bhatia322edfa2013-10-02 10:04:06 -040049 def save(self, *args, **kwargs):
50 super(PlCoreBase, self).save(*args, **kwargs)
51
52 # Tell the observer that the source database has been updated
53 EventSender().fire()
Scott Baker13acdd62013-05-08 17:42:56 -070054
Sapan Bhatia322edfa2013-10-02 10:04:06 -040055 self.__initial = self._dict
56
57 @property
58 def _dict(self):
59 return model_to_dict(self, fields=[field.name for field in
60 self._meta.fields])
Scott Baker13acdd62013-05-08 17:42:56 -070061
Siobhan Tully4bc09f22013-04-10 21:15:21 -040062
63