blob: 30d4df3f6ca9078618857f57b91d5e93fdc5eb92 [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)
Tony Mackb0d97422013-06-10 09:57:45 -040011 enacted = models.DateTimeField(null=True, default=None)
Siobhan Tully4bc09f22013-04-10 21:15:21 -040012
13 class Meta:
14 abstract = True
15 app_label = "core"
16
Scott Baker13acdd62013-05-08 17:42:56 -070017 def __init__(self, *args, **kwargs):
18 super(PlCoreBase, self).__init__(*args, **kwargs)
19 self.__initial = self._dict
20
21 @property
Siobhan Tully73291342013-05-10 10:50:08 -040022 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)
27
28 @property
29 def has_changed(self):
30 return bool(self.diff)
31
32 @property
33 def changed_fields(self):
34 return self.diff.keys()
35
36 def get_field_diff(self, field_name):
37 return self.diff.get(field_name, None)
38
39 def save(self, *args, **kwargs):
40 super(PlCoreBase, self).save(*args, **kwargs)
Sapan Bhatia66f4e612013-07-02 12:12:38 -040041
42 # Tell the observer that the source database has been updated
43 EventSender().fire()
44
Scott Baker13acdd62013-05-08 17:42:56 -070045 self.__initial = self._dict
46
47 @property
Siobhan Tully73291342013-05-10 10:50:08 -040048 def _dict(self):
49 return model_to_dict(self, fields=[field.name for field in
Scott Baker13acdd62013-05-08 17:42:56 -070050 self._meta.fields])
51
Siobhan Tully4bc09f22013-04-10 21:15:21 -040052
53