我有一个使用Django和Django Rest框架开发的应用程序。我想将django-reversion功能添加到我的应用程序中。
我已经尝试http://django-reversion.readthedocs.org/en/latest/api.html#low-level-api,但我未能对我的应用进行具体更改。
下面是应用程序的模块,如果它们被删除,我希望包含Django-reversion来恢复对象。如何为以下模块设置django-reversion配置
admin.py: -
from django.contrib import admin
from.models import Category
admin.site.register(Category)
models.py: -
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=64, unique=True)
def __unicode__(self):
return self.name
serializers.py: -
from rest_framework import serializers
from .models import Category
class CategorySerializer(serializers.ModelSerializer):
courses = serializers.HyperlinkedRelatedField(
many=True
read_only=True
view_name='course-detail'
)
class Meta:
model = Category
fields = ('pk', 'name', 'courses',)
urls.py: -
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from .import views
from django.conf.urls import include
category_list = views.CategoryViewSet.as_view({
'get': 'list',
'post': 'create'
})
category_detail = views.CategoryViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy',
})
urlpatterns = format_suffix_patterns([
url(r'^categories/$',
category_list,
name='category-list'),
url(r'^categories/(?P<pk>[0-9]+)/$',
category_detail,
name='category-detail'),
])
urlpatterns += [
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
views.py: -
from rest_framework import permissions
from rest_framework import viewsets
from .models import Category
from .serializers import CategorySerializer
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.all()
serializer_class = CategorySerializer
permission_classes = (permissions.IsAuthenticatedorReadOnly,)
答案 0 :(得分:5)
The simplest way to create revisions is to use reversion.middleware.RevisionMiddleware。这将自动包装修订中的每个请求,确保将对模型的所有更改添加到其版本历史记录中。
要启用修订中间件,只需将其添加到
MIDDLEWARE_CLASSES
设置,如下所示:
MIDDLEWARE_CLASSES = (
'reversion.middleware.RevisionMiddleware',
# Other middleware goes here...
)
任何更复杂的事情都需要通过您的代码添加API调用,以您决定的方式包装特定的save
调用。
答案 1 :(得分:0)
<强> admin.py 强>
from django.contrib import admin
from.models import Category
import reversion
class BaseReversionAdmin(reversion.VersionAdmin):
pass
admin.site.register(Category, BaseReversionAdmin)
还添加了对installed_apps和middlewareclasses的恢复。
最后,我可以看到&#34;恢复删除的对象按钮&#34;。