Skip to content

Commit 32e6289

Browse files
RealOrangeOneRoss Mechanic
authored andcommitted
Don't resolve relationships for history objects (#479)
* Don't resolve relationships for history objects * Fetch values from instances rather than history objects * Remove unnecessary `in` check This will always evaluate to true, anyway * Don't index current values unnecessarily * Correct black formatting errors
1 parent 4592f02 commit 32e6289

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

simple_history/models.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from django.apps import apps
1010
from django.conf import settings
1111
from django.contrib import admin
12+
from django.core.serializers import serialize
1213
from django.db import models
1314
from django.db.models import Q
1415
from django.db.models.fields.proxy import OrderWrt
@@ -24,9 +25,15 @@
2425
from .manager import HistoryDescriptor
2526
from .signals import post_create_historical_record, pre_create_historical_record
2627

28+
import json
29+
2730
registered_models = {}
2831

2932

33+
def model_to_dict(model):
34+
return json.loads(serialize("json", [model]))[0]["fields"]
35+
36+
3037
def default_get_user(request, **kwargs):
3138
try:
3239
return request.user
@@ -461,18 +468,15 @@ def diff_against(self, old_history):
461468

462469
changes = []
463470
changed_fields = []
464-
instance_fields = [field.name for field in self.instance._meta.fields]
465-
old_instance_fields = [
466-
field.name for field in old_history.instance._meta.fields
467-
]
468-
for field in self._meta.fields:
469-
if field.name in instance_fields and field.name in old_instance_fields:
470-
old_value = getattr(old_history, field.name, "")
471-
new_value = getattr(self, field.name)
471+
old_values = model_to_dict(old_history.instance)
472+
current_values = model_to_dict(self.instance)
473+
for field, new_value in current_values.items():
474+
if field in old_values:
475+
old_value = old_values[field]
472476
if old_value != new_value:
473-
change = ModelChange(field.name, old_value, new_value)
477+
change = ModelChange(field, old_value, new_value)
474478
changes.append(change)
475-
changed_fields.append(field.name)
479+
changed_fields.append(field)
476480

477481
return ModelDelta(changes, changed_fields, old_history, self)
478482

0 commit comments

Comments
 (0)