Siobhan Tully | 4bc09f2 | 2013-04-10 21:15:21 -0400 | [diff] [blame] | 1 | import os |
| 2 | from django.db import models |
Scott Baker | 13acdd6 | 2013-05-08 17:42:56 -0700 | [diff] [blame] | 3 | from django.forms.models import model_to_dict |
Siobhan Tully | 4bc09f2 | 2013-04-10 21:15:21 -0400 | [diff] [blame] | 4 | |
| 5 | class PlCoreBase(models.Model): |
| 6 | |
| 7 | created = models.DateTimeField(auto_now_add=True) |
| 8 | updated = models.DateTimeField(auto_now=True) |
Tony Mack | b0d9742 | 2013-06-10 09:57:45 -0400 | [diff] [blame^] | 9 | enacted = models.DateTimeField(null=True, default=None) |
Siobhan Tully | 4bc09f2 | 2013-04-10 21:15:21 -0400 | [diff] [blame] | 10 | |
| 11 | class Meta: |
| 12 | abstract = True |
| 13 | app_label = "core" |
| 14 | |
Scott Baker | 13acdd6 | 2013-05-08 17:42:56 -0700 | [diff] [blame] | 15 | def __init__(self, *args, **kwargs): |
| 16 | super(PlCoreBase, self).__init__(*args, **kwargs) |
| 17 | self.__initial = self._dict |
| 18 | |
| 19 | @property |
Siobhan Tully | 7329134 | 2013-05-10 10:50:08 -0400 | [diff] [blame] | 20 | def diff(self): |
| 21 | d1 = self.__initial |
| 22 | d2 = self._dict |
| 23 | diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]] |
| 24 | return dict(diffs) |
| 25 | |
| 26 | @property |
| 27 | def has_changed(self): |
| 28 | return bool(self.diff) |
| 29 | |
| 30 | @property |
| 31 | def changed_fields(self): |
| 32 | return self.diff.keys() |
| 33 | |
| 34 | def get_field_diff(self, field_name): |
| 35 | return self.diff.get(field_name, None) |
| 36 | |
| 37 | def save(self, *args, **kwargs): |
| 38 | super(PlCoreBase, self).save(*args, **kwargs) |
Scott Baker | 13acdd6 | 2013-05-08 17:42:56 -0700 | [diff] [blame] | 39 | self.__initial = self._dict |
| 40 | |
| 41 | @property |
Siobhan Tully | 7329134 | 2013-05-10 10:50:08 -0400 | [diff] [blame] | 42 | def _dict(self): |
| 43 | return model_to_dict(self, fields=[field.name for field in |
Scott Baker | 13acdd6 | 2013-05-08 17:42:56 -0700 | [diff] [blame] | 44 | self._meta.fields]) |
| 45 | |
Siobhan Tully | 4bc09f2 | 2013-04-10 21:15:21 -0400 | [diff] [blame] | 46 | |
| 47 | |