美文网首页
基于Mixin类重构视图类

基于Mixin类重构视图类

作者: lkning | 来源:发表于2018-02-28 09:24 被阅读0次
    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    from rest_framework import mixins
    from rest_framework import generics
    
    class SnippetList(mixins.ListModelMixin,
                      mixins.CreateModelMixin,
                      generics.GenericAPIView):
        # 雷打不动,必须的
        queryset = Snippet.objects.all()
        serializer_class = SnippetSerializer
    
        def get(self, request, *args, **kwargs):
            return self.list(request, *args, **kwargs)
    
        def post(self, request, *args, **kwargs):
            return self.create(request, *args, **kwargs)
    
    • CreateModelMixin: 定义了创建一个序列对象的方法create(self, request, *args, **kwargs),保存方法perform_create(self, * * * serializer),成功获取请求头的方法:get_success_headers(self, data)
    • ListModelMixin: 定义了一个获取查询集的方法, many=True:list(self, request, *args, **kwargs)
    • RetrieveModelMixin: 定义了一个检索方法,retrieve(self, request, *args, **kwargs)
    • UpdateModelMixin: 更新一个模型实例,update(self, request, *args, **kwargs)
    • DestroyModelMixin: 删除一个模型实例,方法destroy(self, request, *args, **kwargs)
    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    from rest_framework import mixins
    from rest_framework import generics
    # 重构单个实例处理方法
    class SnippetList(mixins.ListModelMixin,
                      mixins.CreateModelMixin,
                      generics.GenericAPIView):
        queryset = Snippet.objects.all()
        serializer_class = SnippetSerializer
    
        def get(self, request, *args, **kwargs):
            return self.list(request, *args, **kwargs)
    
        def post(self, request, *args, **kwargs):
            return self.create(request, *args, **kwargs)
    

    相关文章

      网友评论

          本文标题:基于Mixin类重构视图类

          本文链接:https://www.haomeiwen.com/subject/zgtbxftx.html