@@ -923,12 +923,20 @@ def diff_against(self, old_history, excluded_fields=None, included_fields=None):
923
923
if excluded_fields is None :
924
924
excluded_fields = set ()
925
925
926
+ included_m2m_fields = {field .name for field in old_history ._history_m2m_fields }
926
927
if included_fields is None :
927
928
included_fields = {
928
929
f .name for f in old_history .instance_type ._meta .fields if f .editable
929
930
}
931
+ else :
932
+ included_m2m_fields = included_m2m_fields .intersection (included_fields )
930
933
931
- fields = set (included_fields ).difference (excluded_fields )
934
+ fields = (
935
+ set (included_fields )
936
+ .difference (included_m2m_fields )
937
+ .difference (excluded_fields )
938
+ )
939
+ m2m_fields = set (included_m2m_fields ).difference (excluded_fields )
932
940
933
941
changes = []
934
942
changed_fields = []
@@ -945,11 +953,10 @@ def diff_against(self, old_history, excluded_fields=None, included_fields=None):
945
953
changed_fields .append (field )
946
954
947
955
# Separately compare m2m fields:
948
- for field in old_history . _history_m2m_fields :
956
+ for field in m2m_fields :
949
957
# First retrieve a single item to get the field names from:
950
958
reference_history_m2m_item = (
951
- getattr (old_history , field .name ).first ()
952
- or getattr (self , field .name ).first ()
959
+ getattr (old_history , field ).first () or getattr (self , field ).first ()
953
960
)
954
961
history_field_names = []
955
962
if reference_history_m2m_item :
@@ -963,15 +970,13 @@ def diff_against(self, old_history, excluded_fields=None, included_fields=None):
963
970
if f .editable and f .name not in ["id" , "m2m_history_id" , "history" ]
964
971
]
965
972
966
- old_rows = list (
967
- getattr (old_history , field .name ).values (* history_field_names )
968
- )
969
- new_rows = list (getattr (self , field .name ).values (* history_field_names ))
973
+ old_rows = list (getattr (old_history , field ).values (* history_field_names ))
974
+ new_rows = list (getattr (self , field ).values (* history_field_names ))
970
975
971
976
if old_rows != new_rows :
972
- change = ModelChange (field . name , old_rows , new_rows )
977
+ change = ModelChange (field , old_rows , new_rows )
973
978
changes .append (change )
974
- changed_fields .append (field . name )
979
+ changed_fields .append (field )
975
980
976
981
return ModelDelta (changes , changed_fields , old_history , self )
977
982
0 commit comments