Django 中模型对象的版本追踪


模型历史追踪是一个追踪模型对象变化的功能,它追踪诸如你做了什么更改以及何时删除了对象等信息。它还有助于恢复已删除的模型对象。在本文中,我们将通过一个示例来了解如何在 Django 中追踪模型对象的版本历史。

示例

首先,设置你的项目、应用、URL 和模型。

安装 **django-simple-history** 库:

pip install django-simple-history

在 **settings.py** 中:

INSTALLED_APPS+=[" simple_history"]
MIDDLEWARE = [
   #other middle ware
   'simple_history.middleware.HistoryRequestMiddleware',
]

在这里,我们添加了 **"simple_history"** 模块作为应用和中间件。

因为我们的主要工作是 **models.py** 和 **admin.py**,所以在 **urls.py** 和 **views.py** 中我们不需要做太多事情。

在 **models.py** 中,添加以下内容:

from django.db import models
from simple_history.models import HistoricalRecords

# Create your models here.
class StudentData(models.Model):
   name=models.CharField(max_length=100)
   standard=models.CharField(max_length=100)
   section=models.CharField(max_length=100)
   history = HistoricalRecords()

在这里,我们简单地创建了一个模型和一个 history 字段,它将保存每一次更改。

在 **admin.py** 中,添加以下几行:

from django.contrib import admin
from .models import StudentData
from simple_history.admin import SimpleHistoryAdmin

admin.site.register(StudentData,SimpleHistoryAdmin)

在这里,我们将带有历史追踪功能的模型注册到 admin 中。

现在运行以下命令:

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

现在一切就绪了。**models.py** 中的以上代码将所有历史数据保存在一个字段中,你可以在 **views.py** 或 Django shell 中访问它。

输出

你可以在 **views.py** 或 Django shell 中查询它。

更新于:2021年8月26日

3K+ 浏览量

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告