blob: 08e4047dfa49f6f3c3c78623a178da0b9fd267ac [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
Tony Mackad5ed9e2013-09-25 12:57:02 -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
Tony Mackad5ed9e2013-09-25 12:57:02 -040013 class Meta:
14 abstract = True
15 app_label = "core"
Siobhan Tully4bc09f22013-04-10 21:15:21 -040016
Tony Mackad5ed9e2013-09-25 12:57:02 -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
Tony Mackad5ed9e2013-09-25 12:57:02 -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
Tony Mackad5ed9e2013-09-25 12:57:02 -040028 @property
29 def has_changed(self):
30 return bool(self.diff)
Siobhan Tully73291342013-05-10 10:50:08 -040031
Tony Mackad5ed9e2013-09-25 12:57:02 -040032 @property
33 def changed_fields(self):
34 return self.diff.keys()
Siobhan Tully73291342013-05-10 10:50:08 -040035
Tony Mackad5ed9e2013-09-25 12:57:02 -040036 def get_field_diff(self, field_name):
37 return self.diff.get(field_name, None)
Siobhan Tully73291342013-05-10 10:50:08 -040038
Tony Mackad5ed9e2013-09-25 12:57:02 -040039 def delete(self, *args, **kwds):
40 super(PlCoreBase, self).delete(*args, **kwds)
Sapan Bhatiadbaf1932013-09-03 11:28:52 -040041
Tony Mackad5ed9e2013-09-25 12:57:02 -040042 EventSender().fire({'delete_flag':True,'model':self.__name__})
Sapan Bhatiadbaf1932013-09-03 11:28:52 -040043
Tony Mackad5ed9e2013-09-25 12:57:02 -040044 def save(self, *args, **kwargs):
45 super(PlCoreBase, self).save(*args, **kwargs)
46
47 # Tell the observer that the source database has been updated
48 EventSender().fire()
Sapan Bhatia66f4e612013-07-02 12:12:38 -040049
Tony Mackad5ed9e2013-09-25 12:57:02 -040050 self.__initial = self._dict
Scott Baker13acdd62013-05-08 17:42:56 -070051
Tony Mackad5ed9e2013-09-25 12:57:02 -040052 @property
53 def _dict(self):
54 return model_to_dict(self, fields=[field.name for field in
55 self._meta.fields])
Scott Baker13acdd62013-05-08 17:42:56 -070056
Siobhan Tully4bc09f22013-04-10 21:15:21 -040057
58