# 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