django-simple-history 配置生效需三步:installed_apps 注册、模型继承 historicalrecords 并声明 historical_records = historicalrecords()、执行 migrate;排除字段用 excluded_fields 参数;get_history() 为空主因是未触发 save();admin 中需继承 simplehistoryadmin 才能显示历史链接。

django-simple-history 安装与基础配置是否生效?
安装后必须在 INSTALLED_APPS 中注册,且需确保模型继承了 HistoricalRecords。常见失效原因是只改了模型但忘了加 historical_records = HistoricalRecords() 字段,或漏掉 migrate 步骤。
- 运行
pip install django-simple-history - 在
settings.py的INSTALLED_APPS中添加'simple_history' - 执行
python manage.py makemigrations和python manage.py migrate - 若历史表未生成(如
myapp_mymodel_history),检查迁移文件是否被跳过,或运行python manage.py showmigrations simple_history确认已应用
如何让某个字段不被记录进历史?
默认所有字段都会被快照,但敏感字段(如密码哈希、token)或高频变动字段(如访问计数)应排除。用 HistoricalRecords 的 excluded_fields 参数即可,它接受字段名列表。
- 在模型中定义:
historical_records = HistoricalRecords(excluded_fields=['last_login_at', 'session_token']) - 注意:
excluded_fields只影响新增/更新时的快照内容,不影响历史查询逻辑 - 不支持动态排除(比如按用户角色过滤),若需更细粒度控制,得重写
HistoricalRecords.get_history_queryset()
查询历史版本时,为什么 get_history() 返回空?
最常见原因是对象尚未被修改过——首次创建后没调用 save(),或修改时用了 update() 这类绕过模型层的操作。
-
get_history()只捕获经由模型实例save()触发的变更,不捕获QuerySet.update()、原生 SQL 或 bulk 操作 - 若用
bulk_create()或bulk_update(),需手动调用HistoricalRecords.bulk_history_create()(需 v3.4+) - 检查历史表是否有数据:
MyModel.history.count(),为 0 就说明没触发任何记录行为
如何在 Admin 中显示历史记录链接?
Django Admin 默认不展示历史入口,需显式启用。关键点是继承 SimpleHistoryAdmin,否则点击“历史”按钮会 404。
- 在
admin.py中:from simple_history.admin import SimpleHistoryAdmin from django.contrib import admin from .models import MyModel
@admin.register(MyModel) class MyModelAdmin(SimpleHistoryAdmin): list_display = ['name', 'created_at']
- 若自定义了get_urls() 或重写了 change_view,需确保调用父类方法,否则历史视图路由可能丢失
- 历史页面里的时间戳是 history_date 字段,它基于事务提交时间,不是模型 save() 调用时刻,高并发下可能有毫秒级偏差
历史记录本身不带用户上下文,除非你在中间件里设置了 request.user 并启用 HistoricalRecords(user_related_name=...);这个细节常被忽略,结果查到一堆 None 用户的记录。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











