Skip to content

Commit

Permalink
refactor(history): move get_diff method to APISHistoryTableBase
Browse files Browse the repository at this point in the history
Having the `get_diff` method as part of the historical record itself has
the advantage, that it can be used from different parts of the code.
  • Loading branch information
b1rger committed Apr 25, 2024
1 parent ab83ab9 commit cf9c0c9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 16 deletions.
18 changes: 18 additions & 0 deletions apis_core/history/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,24 @@ def set_version_tag(self, tag: str, include_triples: bool = True):
triple.save()
self.save()

def get_diff(self, other_version=None):
if self.history_type == "-":
return None
version = other_version or self.prev_record
if version:
delta = self.diff_against(version)
else:
delta = self.diff_against(self.__class__())
changes = list(
filter(
lambda x: (x.new != "" or x.old is not None)
and x.field != "id"
and not x.field.endswith("_ptr"),
delta.changes,
)
)
return sorted(changes, key=lambda change: change.field)


class VersionMixin(models.Model):
history = APISHistoricalRecords(
Expand Down
19 changes: 3 additions & 16 deletions apis_core/history/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,24 +57,11 @@ class HistoryLogSerializer(serializers.Serializer):
history_id = serializers.IntegerField()

def get_diff(self, obj):
if obj.history_type == "-":
return None
if obj.prev_record is None:
diff = obj.diff_against(obj.__class__())
else:
diff = obj.diff_against(obj.prev_record)
changed_fields = []
obj_changes = obj.get_diff()
changes = []
for change in diff.changes:
if (
(change.new == "" and change.old is None)
or change.field == "id"
or change.field.endswith("_ptr")
):
continue
changed_fields.append(change.field)
for change in obj_changes:
changes.append(ModelChangeSerializer(change, obj).data)
return {"changed_fields": changed_fields, "changes": changes}
return {"changed_fields": [change.field for change in obj_changes], "changes": changes}

def get_action(self, obj):
match obj.history_type:
Expand Down

0 comments on commit cf9c0c9

Please sign in to comment.