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)
网友评论