Skip to content

Commit

Permalink
Reuse model_to_dict
Browse files Browse the repository at this point in the history
This not only means comparison is done on primitive values, but as a side effect removes the extra query for base models
  • Loading branch information
RealOrangeOne committed Sep 22, 2021
1 parent b108f34 commit ed7dd7d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
11 changes: 9 additions & 2 deletions simple_history/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from django.db import models
from django.db.models import ManyToManyField
from django.db.models.fields.proxy import OrderWrt
from django.forms.models import model_to_dict
from django.urls import reverse
from django.utils import timezone
from django.utils.encoding import smart_str
Expand Down Expand Up @@ -603,9 +604,15 @@ def diff_against(self, old_history, excluded_fields=None, included_fields=None):
changes = []
changed_fields = []

old_values = model_to_dict(old_history, fields=fields)
current_values = model_to_dict(self, fields=fields)

for field in fields:
old_value = getattr(old_history, field)
current_value = getattr(self, field)
try:
old_value = old_values[field]
current_value = current_values[field]
except KeyError:
continue

if old_value != current_value:
changes.append(ModelChange(field, old_value, current_value))
Expand Down
3 changes: 1 addition & 2 deletions simple_history/tests/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -646,8 +646,7 @@ def test_history_diff_includes_changed_fields_of_base_model(self):
r.name = "DonnutsKing"
r.save()
new_record, old_record = r.history.all()
# Two queries due to base lookup
with self.assertNumQueries(2):
with self.assertNumQueries(0):
delta = new_record.diff_against(old_record)
expected_change = ModelChange("name", "McDonna", "DonnutsKing")
self.assertEqual(delta.changed_fields, ["name"])
Expand Down

0 comments on commit ed7dd7d

Please sign in to comment.