blob: 00dc2d03dc695ca5e952e2cd9c57e180d0b31441 [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 Bhatia66f4e612013-07-02 12:12:38 -04004from openstack.event_manager import EventSender
5
Siobhan Tully4bc09f22013-04-10 21:15:21 -04006
7class PlCoreBase(models.Model):
8
9 created = models.DateTimeField(auto_now_add=True)
10 updated = models.DateTimeField(auto_now=True)
11
12 class Meta:
13 abstract = True
14 app_label = "core"
15
Scott Baker13acdd62013-05-08 17:42:56 -070016 def __init__(self, *args, **kwargs):
17 super(PlCoreBase, self).__init__(*args, **kwargs)
18 self.__initial = self._dict
19
20 @property
Siobhan Tully73291342013-05-10 10:50:08 -040021 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)
26
27 @property
28 def has_changed(self):
29 return bool(self.diff)
30
31 @property
32 def changed_fields(self):
33 return self.diff.keys()
34
35 def get_field_diff(self, field_name):
36 return self.diff.get(field_name, None)
37
38 def save(self, *args, **kwargs):
39 super(PlCoreBase, self).save(*args, **kwargs)
Sapan Bhatia66f4e612013-07-02 12:12:38 -040040
41 # Tell the observer that the source database has been updated
42 EventSender().fire()
43
Scott Baker13acdd62013-05-08 17:42:56 -070044 self.__initial = self._dict
45
46 @property
Siobhan Tully73291342013-05-10 10:50:08 -040047 def _dict(self):
48 return model_to_dict(self, fields=[field.name for field in
Scott Baker13acdd62013-05-08 17:42:56 -070049 self._meta.fields])
50
Siobhan Tully4bc09f22013-04-10 21:15:21 -040051
52