使用中间件
如果您通过 django 视图编辑数据库,HistoryRequestMiddleware中间件会自动处理
self.client.post(reverse("frontend:application_create"), data=data)
而不是直接在命令行中
myapp.models.Application.objects.create(name='My application')
示例(单元测试)
这是一个单元测试,用于找出哪个用户更改了记录(受django-simple-history 单元测试的启发)。
# tests.py
class HistoryTestCase(TestCase):
def test_changed_by(self):
"""Find out which user changed a record"""
# First, let's create and log a user in
user = get_user_model().objects.create_user("jimihendrix", password="pwtest")
self.client.login(username="jimihendrix", password="pwtest")
# Let's create a new entry
data = {"name": "A new application", }
response = self.client.post(reverse("frontend:application_create"), data=data)
# This how you know who changed the record
self.assertEqual(app1.history.earliest().history_user, user)
self.assertEqual(app1.history.last().history_user, user)
self.assertEqual(app1.history.first().history_user, user)
# urls.py
# ...
path('application/create/', old_views.ApplicationCreate.as_view(), name='application_create'),
# ...
# models.py
class Application(models.Model):
name = models.CharField(max_length=200)