使用GenericAPIView序列化
修改blogs目录下的views.py,需要结合mixin方法一起使用
from rest_framework import generics
from rest_framework import mixins
from .serializers import ArticleSerializer
from .models import Article
class ArticleListView(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = Article.objects.all()[:5]
serializer_class = ArticleSerializer
# authentication_classes = (TokenAuthentication, )
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
运行项目可以在接口页面看到自动渲染了form表单提交,而且user字段下新增了avatar自动并自带域名路径
Mixin的方法介绍
ListModelMixin:使用list方法和get请求绑定
CreateModelMixin:使用create方法和post请求绑定
RetrieveModelMixin:使用retrieve方法,表示返回单个数据
UpdateModelMixin:使用update方法和put/patch请求绑定
DestroyModelMixin:使用destroy方法和delete请求绑定
使用ListCreateAPIView
除此之外还有更简便的方法ListCreateAPIView代替,看源码继承了mixins.ListModelMixin,mixins.CreateModelMixin,GenericAPIView
from rest_framework import generics
from .serializers import ArticleSerializer
from .models import Article
class ArticleListView(generics.ListCreateAPIView):
queryset = Article.objects.all()[:5]
serializer_class = ArticleSerializer
# authentication_classes = (TokenAuthentication, )
版权声明:如无特殊说明,文章均为本站原创,转载请注明出处
本文链接:http://zhangyanc.club/subject/article/GenericAPIView/
许可协议:署名-非商业性使用 4.0 国际许可协议