When I inherit from admin.ModelAdmin, in history on admin page I can see what fields has been changed. However, now I need to use django-simple-history to track all my model changes. Now, for admin, I inherit for simple_history.SimpleHistoryAdmin. Whilst I can see all of the model changes and revert them, I cannot see, which fields were changed. Is it possible to add that handy functionality to SimpleHistoryAdmin?
问问题
1889 次
4 回答
3
我找到了解决这个问题的方法。我添加了一个 ModelAdmin 方法并使用 History Diffing 在 Change history 表中添加了一个自定义字段。
history_list_display = ['changed_fields']
def changed_fields(self, obj):
if obj.prev_record:
delta = obj.diff_against(obj.prev_record)
return delta.changed_fields
return None
于 2020-01-22T21:17:43.360 回答
3
您需要的是history_list_display
管理员中的字段。包含在其中的字段列表history_list_display
将显示在历史页面中,并带有相应的条目。
像这样的东西:
class SomeAdmin(admin.ModelAdmin):
def some_user_defined(self, obj):
return "something"
date_hierarchy = 'created_at'
search_fields = ['field1', 'field2']
list_display = ('field1', 'field2',)
list_filter = ('field1',)
history_list_display = ('field1', 'field2', 'some_user_defined',)
这将显示field1
,field2
和comment
,user
和reason
于 2019-01-10T09:36:36.303 回答
1
如果您不仅要查看根据 Rafi 注释更改的字段的名称以及更改的值,则下一个代码将执行此操作:
def changed_fields_with_values(self, obj):
fields = ""
if obj.prev_record:
delta = obj.diff_against(obj.prev_record)
for change in delta.changes:
fields += str("{} changed from {} to {}".format(change.field, change.old, change.new))
return fields
return None
于 2021-08-23T08:27:39.143 回答
0
与 Rafi 之前的解决方案类似,但使用数组更优雅地列出记录更改:
def list_changes(self, obj):
diff = []
if obj.prev_record:
delta = obj.diff_against(obj.prev_record)
for change in delta.changes:
diff.append("<b>* {}:</b> changed from `{}` to `{}`".format(change.field, change.old, change.new))
return mark_safe("\n<br>".join(diff))
于 2022-01-13T16:27:04.387 回答