上一部分代码在序列化部分
类继承顺序
############### mixins.py ################
# 类中调用的方法均在 GenericAPIView 类中实现,所以下列类需要结合 GenericAPIView 使用
class ListModelMixin(object) # 查看继承类
def list(self, request, *args, **kwargs)
class CreateModelMixin(object) # 添加继承类
def create(self, request, *args, **kwargs
class RetrieveModelMixin(object) # 查看单条继承类
def retrieve(self, request, *args, **kwargs)
class UpdateModelMixin(object) # 更新单条继承类
def update(self, request, *args, **kwargs)
class DestroyModelMixin(object) # 删除单条继承类
def destroy(self, request, *args, **kwargs)
############### generics.py ###############
class GenericAPIView(views.APIView)
pass # 这个是懒得写,主要结合上边的使用
class ListCreateAPIView(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
GenericAPIView):
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
)
############### viewsets.py ###############
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet)
pass # 这个是真pass
class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
pass # 这个也是真pass
class ViewSetMixin(object):
def as_view(cls, actions=None, **initkwargs)
def view(request, *args, **kwargs):
def initialize_request(self, request, *args, **kwargs):
自己重构get,put等函数,全部手写,代码重复率很高:
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from django.shortcuts import HttpResponse
from django.core import serializers
from rest_framework import serializers
class BookSerializers(serializers.ModelSerializer):
class Meta:
model=Book
fields="__all__"
#depth=1
class PublshSerializers(serializers.ModelSerializer):
class Meta:
model=Publish
fields="__all__"
depth=1
class BookViewSet(APIView):
def get(self,request,*args,**kwargs):
book_list=Book.objects.all()
# 文本类型,这个是和上面的连接有关,后面的参数context,HyperlinkedIdentityField,这个是设置了连接的时候,进行的操作
bs=BookSerializers(book_list,many=True,context={'request': request})
return Response(bs.data)
def post(self,request,*args,**kwargs):
print(request.data)
bs=BookSerializers(data=request.data,many=False)
if bs.is_valid():
print(bs.validated_data)
bs.save()
return Response(bs.data)
else:
return HttpResponse(bs.errors)
class BookDetailViewSet(APIView):
def get(self,request,pk):
book_obj=Book.objects.filter(pk=pk).first()
bs=BookSerializers(book_obj,context={'request': request})
return Response(bs.data)
def put(self,request,pk):
book_obj=Book.objects.filter(pk=pk).first()
bs=BookSerializers(book_obj,data=request.data,context={'request': request})
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return HttpResponse(bs.errors)
class PublishViewSet(APIView):
def get(self,request,*args,**kwargs):
publish_list=Publish.objects.all()
bs=PublshSerializers(publish_list,many=True,context={'request': request})
return Response(bs.data)
def post(self,request,*args,**kwargs):
bs=PublshSerializers(data=request.data,many=False)
if bs.is_valid():
# print(bs.validated_data)
bs.save()
return Response(bs.data)
else:
return HttpResponse(bs.errors)
class PublishDetailViewSet(APIView):
def get(self,request,pk):
publish_obj=Publish.objects.filter(pk=pk).first()
bs=PublshSerializers(publish_obj,context={'request': request})
return Response(bs.data)
def put(self,request,pk):
publish_obj=Publish.objects.filter(pk=pk).first()
bs=PublshSerializers(publish_obj,data=request.data,context={'request': request})
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return HttpResponse(bs.errors)
继承mixins的ListModelMixin,CreateModelMixin等类
from rest_framework import mixins
from rest_framework import generics
class BookViewSet(mixins.ListModelMixin, # 查看继承类
mixins.CreateModelMixin, # 添加继承类
generics.GenericAPIView):
queryset = Book.objects.all() # 数据库
serializer_class = BookSerializers # 序列化类
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class BookDetailViewSet(mixins.RetrieveModelMixin, # 查看单条继承类
mixins.UpdateModelMixin, # 更新单条继承类
mixins.DestroyModelMixin, # 删除单条继承类
generics.GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializers
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
通过使用mixin类,我们使用更少的代码重写了这些视图,但我们还可以再进一步。REST框架提供了一组已经混合好(mixed-in)的通用视图,我们可以使用它来简化我们的views.py
模块。
from rest_framework import mixins
from rest_framework import generics
class BookViewSet(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializers
class BookDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializers
class PublishViewSet(generics.ListCreateAPIView):
queryset = Publish.objects.all()
serializer_class = PublshSerializers
class PublishDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
queryset = Publish.objects.all()
serializer_class = PublshSerializers
urls.py:
url(r'^books/$', views.BookViewSet.as_view({"get":"list","post":"create"}),name="book_list"),
url(r'^books/(?P\d+)$', views.BookViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
}),name="book_detail"),
views.py:
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializers
urls.py同上
views.py
from rest_framework.routers import DefaultRouter
router = DefaultRouter() # 实例化
router.register(r'school', views.SchoolView) # 注册
urlpatterns += router.urls # 在urlpatterns中添加