「Django」rest_framework学习系列-视图

方式一

1.settings设置

INSTALLED_APPS = [
    ...
    'rest_framework',
]
View Code

2.views设置

from rest_framework.response import Response

class PagesView(APIView):
    def get(self,request,*args,**kwargs):
    ...
    ...    
    return Response(ser.data)
View Code

方式二

1.urls:

re_path(r'^(?P<version>[v1|v2]+)/pages/$',PagesView.as_view({'get':'list'}),),
View Code

2.views:

from rest_framework.viewsets import GenericViewSet
get请求执行list方法
class PagesView(GenericViewSet):
    queryset = models.UserInfo.objects.all()
    serializer_class = pages.PagesSerializer #自己写好的类
    pagination_class = MyPageNumberPagination #同上
    def list(self,request,*args,**kwargs):
        # 获取所有数据
        m = self.get_queryset()
        #创建分页对象并在数据库中获取分页的数据
        pa_info = self.paginate_queryset(m)
        #对数据进行序列化
        ser = self.get_serializer(instance=pa_info,many=True)
    return Response(ser.data)
View Code

方式三

1.urls:

re_path(r'^(?P<version>[v1|v2]+)/pages/$',PagesView.as_view({'get':'list','post':'create'}),),
re_path(r'^(?P<version>[v1|v2]+)/pages/(?P<pk>\d+)$', PagesView.as_view({'get': 'retrieve', 'delete': 'destroy','put':'update','patch':'partial_update'}), ),
View Code

2.views:

from rest_framework.viewsets import ModelViewSet(继承了6个类,继承越多,代码需要写的越少)
from rest_framework.mixins import ListModelMixin,CreateModelMixin(被上面的类继承)

class PagesView(ModelViewSet):
    queryset = models.UserInfo.objects.all()
    serializer_class = pages.PagesSerializer
    pagination_class = MyPageNumberPagination
总结:
a.增删改查用方式三
b.增删 ListModelMixin/CreateModelMixin,GenericViewSet
c.复杂逻辑 GenericViewSet或APIView
View Code

 

posted @ 2019-02-19 17:41  子谦0618  阅读(91)  评论(0编辑  收藏  举报