blob: 62bcb75d81bff9a56f36dbf8dca2c721e2dad570 [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)
Siobhan Tully4bc09f22013-04-10 21:15:21 -040011
Sapan Bhatia541f9532013-09-03 11:43:55 -040012 class Meta:
13 abstract = True
14 app_label = "core"
Siobhan Tully4bc09f22013-04-10 21:15:21 -040015
Sapan Bhatia541f9532013-09-03 11:43:55 -040016 def __init__(self, *args, **kwargs):
17 super(PlCoreBase, self).__init__(*args, **kwargs)
18 self.__initial = self._dict
Scott Baker13acdd62013-05-08 17:42:56 -070019
Sapan Bhatia541f9532013-09-03 11:43:55 -040020 @property
21 def diff(self):
22 d1 = self.__initial
23 d2 = self._dict
24 diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
25 return dict(diffs)
Siobhan Tully73291342013-05-10 10:50:08 -040026
Sapan Bhatia541f9532013-09-03 11:43:55 -040027 @property
28 def has_changed(self):
29 return bool(self.diff)
Siobhan Tully73291342013-05-10 10:50:08 -040030
Sapan Bhatia541f9532013-09-03 11:43:55 -040031 @property
32 def changed_fields(self):
33 return self.diff.keys()
Siobhan Tully73291342013-05-10 10:50:08 -040034
Sapan Bhatia541f9532013-09-03 11:43:55 -040035 def get_field_diff(self, field_name):
36 return self.diff.get(field_name, None)
Siobhan Tully73291342013-05-10 10:50:08 -040037
Sapan Bhatiadbaf1932013-09-03 11:28:52 -040038 def delete(self, *args, **kwds):
Sapan Bhatia541f9532013-09-03 11:43:55 -040039 super(PlCoreBase, self).delete(*args, **kwds)
Sapan Bhatiadbaf1932013-09-03 11:28:52 -040040
41 EventSender().fire({'delete_flag':True,'model':self.__name__})
42
Sapan Bhatia541f9532013-09-03 11:43:55 -040043 def save(self, *args, **kwargs):
44 super(PlCoreBase, self).save(*args, **kwargs)
45
46 # Tell the observer that the source database has been updated
47 EventSender().fire()
Sapan Bhatia66f4e612013-07-02 12:12:38 -040048
Sapan Bhatia541f9532013-09-03 11:43:55 -040049 self.__initial = self._dict
Scott Baker13acdd62013-05-08 17:42:56 -070050
Sapan Bhatia541f9532013-09-03 11:43:55 -040051 @property
52 def _dict(self):
53 return model_to_dict(self, fields=[field.name for field in
54 self._meta.fields])
Scott Baker13acdd62013-05-08 17:42:56 -070055
Siobhan Tully4bc09f22013-04-10 21:15:21 -040056
57