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) |
| 9 | |
| 10 | class Meta: |
| 11 | abstract = True |
| 12 | app_label = "core" |
| 13 | |
Scott Baker | 13acdd6 | 2013-05-08 17:42:56 -0700 | [diff] [blame] | 14 | def __init__(self, *args, **kwargs): |
| 15 | super(PlCoreBase, self).__init__(*args, **kwargs) |
| 16 | self.__initial = self._dict |
| 17 | |
| 18 | @property |
| 19 | def diff(self):
|
| 20 | d1 = self.__initial
|
| 21 | d2 = self._dict
|
| 22 | diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
|
| 23 | return dict(diffs)
|
| 24 |
|
| 25 | @property
|
| 26 | def has_changed(self):
|
| 27 | return bool(self.diff)
|
| 28 |
|
| 29 | @property
|
| 30 | def changed_fields(self):
|
| 31 | return self.diff.keys()
|
| 32 |
|
| 33 | def get_field_diff(self, field_name):
|
| 34 | return self.diff.get(field_name, None)
|
| 35 |
|
| 36 | def save(self, *args, **kwargs):
|
| 37 | super(PlCoreBase, self).save(*args, **kwargs)
|
| 38 | self.__initial = self._dict |
| 39 | |
| 40 | @property |
| 41 | def _dict(self):
|
| 42 | return model_to_dict(self, fields=[field.name for field in
|
| 43 | self._meta.fields]) |
| 44 | |
Siobhan Tully | 4bc09f2 | 2013-04-10 21:15:21 -0400 | [diff] [blame] | 45 | |
| 46 | |