mirror of
https://github.com/pacnpal/thrillwiki_django_no_react.git
synced 2025-12-20 12:51:09 -05:00
40 lines
1.2 KiB
Python
40 lines
1.2 KiB
Python
# history_tracking/mixins.py
|
|
|
|
|
|
class HistoricalChangeMixin:
|
|
@property
|
|
def prev_record(self):
|
|
"""Get the previous record for this instance"""
|
|
try:
|
|
return type(self).objects.filter(
|
|
history_date__lt=self.history_date,
|
|
id=self.id
|
|
).order_by('-history_date').first()
|
|
except (AttributeError, TypeError):
|
|
return None
|
|
|
|
@property
|
|
def diff_against_previous(self):
|
|
prev_record = self.prev_record
|
|
if not prev_record:
|
|
return {}
|
|
|
|
changes = {}
|
|
for field in self.__dict__:
|
|
if field not in [
|
|
"history_date",
|
|
"history_id",
|
|
"history_type",
|
|
"history_user_id",
|
|
"history_change_reason",
|
|
"history_type",
|
|
] and not field.startswith("_"):
|
|
try:
|
|
old_value = getattr(prev_record, field)
|
|
new_value = getattr(self, field)
|
|
if old_value != new_value:
|
|
changes[field] = {"old": old_value, "new": new_value}
|
|
except AttributeError:
|
|
continue
|
|
return changes
|