标签:style create objects port mil 路由 load ted gen
在原来modelserializers基础上进行了一次封装方便了使用
# author class AuthorModelSerializers(serializers.ModelSerializer): class Meta: model = models.Author fields = "__all__" from rest_framework import mixins from rest_framework import generics class AuthorView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): # queryset serializer 这两个方法一定要定义成这个不然取不到值 queryset = models.Author.objects.all() serializer_class = AuthorModelSerializers 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 AuthorDetaiView(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin, generics.GenericAPIView): # queryset serializer 这两个方法一定要定义成这个不然取不到值 queryset = models.Author.objects.all() serializer_class = AuthorModelSerializers def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def delete(self,request,*args,**kwargs): return self.destroy(request,*args,**kwargs) def put(self,request,*args,**kwargs): return self.update(request,*args,**kwargs)
使用通用的基于类的视图(封装第三次减少了代码量)
# author class AuthorModelSerializers(serializers.ModelSerializer): class Meta: model = models.Author fields = "__all__" from rest_framework import mixins from rest_framework import generics # 封装了3层 class AuthorView(generics.ListCreateAPIView): # queryset serializer 这两个方法一定要定义成这个不然取不到值 queryset = models.Author.objects.all() serializer_class = AuthorModelSerializers # 封装了3层 class AuthorDetaiView(generics.RetrieveUpdateDestroyAPIView): # queryset serializer 这两个方法一定要定义成这个不然取不到值 queryset = models.Author.objects.all() serializer_class = AuthorModelSerializers
使用视图集
viewsets.ModelViewSet
原理:
# author
class AuthorModelSerializers(serializers.ModelSerializer):
class Meta:
model = models.Author
fields = "__all__"
from rest_framework import mixins
from rest_framework import generics
class AuthorView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
# queryset serializer 这两个方法一定要定义成这个不然取不到值
queryset = models.Author.objects.all()
serializer_class = AuthorModelSerializers
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 AuthorDetaiView(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin,
generics.GenericAPIView):
# queryset serializer 这两个方法一定要定义成这个不然取不到值
queryset = models.Author.objects.all()
serializer_class = AuthorModelSerializers
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def delete(self,request,*args,**kwargs):
return self.destroy(request,*args,**kwargs)
def put(self,request,*args,**kwargs):
return self.update(request,*args,**kwargs)
标签:style create objects port mil 路由 load ted gen
原文地址:https://www.cnblogs.com/Rivend/p/11832388.html