blob: 94c3d5ad5fbc5c18771063c0d775b50433a7a511 [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
Scott Bakerc1c45f82014-01-21 16:23:51 -08004from django.core.urlresolvers import reverse
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -04005# This is a no-op if observer_disabled is set to 1 in the config file
6from observer import *
Siobhan Tully4bc09f22013-04-10 21:15:21 -04007
8class PlCoreBase(models.Model):
9
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040010 created = models.DateTimeField(auto_now_add=True)
11 updated = models.DateTimeField(auto_now=True)
12 enacted = models.DateTimeField(null=True, default=None)
Siobhan Tully4bc09f22013-04-10 21:15:21 -040013
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040014 class Meta:
15 abstract = True
16 app_label = "core"
Siobhan Tully4bc09f22013-04-10 21:15:21 -040017
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040018 def __init__(self, *args, **kwargs):
19 super(PlCoreBase, self).__init__(*args, **kwargs)
20 self.__initial = self._dict
Scott Baker13acdd62013-05-08 17:42:56 -070021
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040022 @property
23 def diff(self):
24 d1 = self.__initial
25 d2 = self._dict
26 diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
27 return dict(diffs)
Siobhan Tully73291342013-05-10 10:50:08 -040028
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040029 @property
30 def has_changed(self):
31 return bool(self.diff)
Siobhan Tully73291342013-05-10 10:50:08 -040032
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040033 @property
34 def changed_fields(self):
35 return self.diff.keys()
Siobhan Tully73291342013-05-10 10:50:08 -040036
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040037 def get_field_diff(self, field_name):
38 return self.diff.get(field_name, None)
Siobhan Tully73291342013-05-10 10:50:08 -040039
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040040 def delete(self, *args, **kwds):
41 super(PlCoreBase, self).delete(*args, **kwds)
Sapan Bhatiadbaf1932013-09-03 11:28:52 -040042
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040043 # This is a no-op if observer_disabled is set
Scott Bakerc1c45f82014-01-21 16:23:51 -080044 notify_observer(model=self, delete=True, pk=self.pk)
Sapan Bhatiadbaf1932013-09-03 11:28:52 -040045
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040046 def save(self, *args, **kwargs):
47 super(PlCoreBase, self).save(*args, **kwargs)
48
49 # This is a no-op if observer_disabled is set
50 notify_observer()
Sapan Bhatia66f4e612013-07-02 12:12:38 -040051
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040052 self.__initial = self._dict
Scott Baker13acdd62013-05-08 17:42:56 -070053
Sapan Bhatia9c2c8fa2013-10-16 13:26:05 -040054 @property
55 def _dict(self):
56 return model_to_dict(self, fields=[field.name for field in
57 self._meta.fields])
Scott Baker13acdd62013-05-08 17:42:56 -070058
Siobhan Tully4bc09f22013-04-10 21:15:21 -040059
60