django-reversion的使用

2020-04-09  本文已影响0人  DjangoUnchained
1. 介绍

django-reversion是为django提供历史版本管理的第三方库。

2. 我的django依赖
Django == 2.2.11
django-reversion >=3.0.5
djangorestframework== 3.10.3
3. model注册举例
import reversion

@reversion.register()
class BaseTable(models.Model):
    """
    """

    class Meta:
        abstract = True
        verbose_name = "公共字段表"
        db_table = 'BaseTable'

    create_time = models.DateTimeField('创建时间', auto_now_add=True)
    update_time = models.DateTimeField('更新时间', auto_now=True)
4. View举例
from reversion.views import RevisionMixin
from rest_framework.viewsets import ModelViewSet

class APIView(RevisionMixin, ModelViewSet):
    def list(self, request, *args, **kwargs):
        pass
    def create(self, request, *args, **kwargs):
        pass
    def update(self, request, *args, **kwargs):
        pass
    def destroy(self, request, *args, **kwargs):
        pass
5. model初始化
# 命令
python manage.py createinitialrevisions
# 执行结果
Creating revisions for 接口信息
- Created 148 / 148
6. 查询具体对象或者model中删除的历史记录
from django.shortcuts import get_object_or_404
from reversion.models import Version

# version_obj_id指某一个具体对象的id,model为要查询的table
instance = get_object_or_404(model, id=version_obj_id)
queryset = Version.objects.get_for_object(instance)

# 查询model中删除历史
queryset = Version.objects.get_deleted(model)
7. 恢复历史记录
from reversion.models import Version

# version_id为上一步查询出的历史记录的id
reversion = Version.objects.filter(id=version_id)
reversion[0].revision.revert()
最后
上一篇下一篇

猜你喜欢

热点阅读