blob: dcc3c39d29bad7d6868a44d7c5f07505cb514d8f [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 Bhatia541f9532013-09-03 11:43:55 -04009 created = models.DateTimeField(auto_now_add=True)
10 updated = models.DateTimeField(auto_now=True)
Sapan Bhatia322edfa2013-10-02 10:04:06 -040011 enacted = models.DateTimeField(null=True, default=None)
Siobhan Tully4bc09f22013-04-10 21:15:21 -040012
Sapan Bhatia541f9532013-09-03 11:43:55 -040013 class Meta:
14 abstract = True
15 app_label = "core"
Siobhan Tully4bc09f22013-04-10 21:15:21 -040016
Sapan Bhatia541f9532013-09-03 11:43:55 -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 Bhatia541f9532013-09-03 11:43:55 -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 Bhatia541f9532013-09-03 11:43:55 -040028 @property
29 def has_changed(self):
30 return bool(self.diff)
Siobhan Tully73291342013-05-10 10:50:08 -040031
Sapan Bhatia541f9532013-09-03 11:43:55 -040032 @property
33 def changed_fields(self):
34 return self.diff.keys()
Siobhan Tully73291342013-05-10 10:50:08 -040035
Sapan Bhatia541f9532013-09-03 11:43:55 -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 Bhatiadbaf1932013-09-03 11:28:52 -040039 def delete(self, *args, **kwds):
Sapan Bhatia541f9532013-09-03 11:43:55 -040040 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 Bhatia541f9532013-09-03 11:43:55 -040048 def save(self, *args, **kwargs):
49 super(PlCoreBase, self).save(*args, **kwargs)
50
51 # Tell the observer that the source database has been updated
Siobhan Tullyce652d02013-10-08 21:52:35 -040052 #EventSender().fire()
Sapan Bhatia66f4e612013-07-02 12:12:38 -040053
Sapan Bhatia541f9532013-09-03 11:43:55 -040054 self.__initial = self._dict
Scott Baker13acdd62013-05-08 17:42:56 -070055
Sapan Bhatia541f9532013-09-03 11:43:55 -040056 @property
57 def _dict(self):
58 return model_to_dict(self, fields=[field.name for field in
59 self._meta.fields])
Scott Baker13acdd62013-05-08 17:42:56 -070060
Siobhan Tully4bc09f22013-04-10 21:15:21 -040061
62