Skip to content

Commit 9efbfab

Browse files
committed
Fixed KeyError when cleaning duplicate history
...on models with `excluded_fields`.
1 parent 869ae77 commit 9efbfab

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

CHANGES.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ Unreleased
1010
- Add basic support for many-to-many fields (gh-399)
1111
- Added support for Django 4.1 (gh-1021)
1212
- Added ``tracked_fields`` attribute to historical models (gh-1038)
13+
- Fixed ``KeyError`` when running ``clean_duplicate_history`` on models with ``excluded_fields`` (gh-1038)
1314

1415
3.1.1 (2022-04-23)
1516
------------------

simple_history/models.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -928,9 +928,7 @@ def diff_against(self, old_history, excluded_fields=None, included_fields=None):
928928

929929
included_m2m_fields = {field.name for field in old_history._history_m2m_fields}
930930
if included_fields is None:
931-
included_fields = {
932-
f.name for f in old_history.instance_type._meta.fields if f.editable
933-
}
931+
included_fields = {f.name for f in old_history.tracked_fields if f.editable}
934932
else:
935933
included_m2m_fields = included_m2m_fields.intersection(included_fields)
936934

simple_history/tests/tests/test_commands.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,25 @@ def test_auto_cleanup_with_excluded_fields(self):
410410
)
411411
self.assertEqual(Poll.history.all().count(), 1)
412412

413+
def test_auto_cleanup_for_model_with_excluded_fields(self):
414+
p = PollWithExcludeFields.objects.create(
415+
question="Will this be deleted?", pub_date=datetime.now()
416+
)
417+
self.assertEqual(PollWithExcludeFields.history.all().count(), 1)
418+
p.pub_date = p.pub_date + timedelta(days=1)
419+
p.save()
420+
self.assertEqual(PollWithExcludeFields.history.all().count(), 2)
421+
out = StringIO()
422+
management.call_command(
423+
self.command_name, auto=True, stdout=out, stderr=StringIO()
424+
)
425+
self.assertEqual(
426+
out.getvalue(),
427+
"Removed 1 historical records for "
428+
"<class 'simple_history.tests.models.PollWithExcludeFields'>\n",
429+
)
430+
self.assertEqual(PollWithExcludeFields.history.all().count(), 1)
431+
413432

414433
class TestCleanOldHistory(TestCase):
415434
command_name = "clean_old_history"

0 commit comments

Comments
 (0)