Django REST framework 视图

上一部分代码在序列化部分

类继承顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
############### mixins.py ################
# 类中调用的方法均在 GenericAPIView 类中实现,所以下列类需要结合 GenericAPIView 使用
class ListModelMixin(object) # 查看继承类
def list(self, request, *args, **kwargs)

class CreateModelMixin(object) # 添加继承类
def create(self, request, *args, **kwargs

class RetrieveModelMixin(object) # 查看单条继承类
def retrieve(self, request, *args, **kwargs)

class UpdateModelMixin(object) # 更新单条继承类
def update(self, request, *args, **kwargs)

class DestroyModelMixin(object) # 删除单条继承类
def destroy(self, request, *args, **kwargs)

############### generics.py ###############
class GenericAPIView(views.APIView)
pass # 这个是懒得写,主要结合上边的使用

class ListCreateAPIView(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericAPIView):
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 RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
GenericAPIView):
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)

def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)

def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
)


############### viewsets.py ###############
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet)
pass # 这个是真pass

class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
pass # 这个也是真pass

class ViewSetMixin(object):
def as_view(cls, actions=None, **initkwargs)
def view(request, *args, **kwargs):
def initialize_request(self, request, *args, **kwargs):

使用混合(mixins)

自己重构get,put等函数,全部手写,代码重复率很高:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from django.shortcuts import HttpResponse
from django.core import serializers
from rest_framework import serializers

class BookSerializers(serializers.ModelSerializer):
class Meta:
model=Book
fields="__all__"
#depth=1


class PublshSerializers(serializers.ModelSerializer):
class Meta:
model=Publish
fields="__all__"
depth=1


class BookViewSet(APIView):
def get(self,request,*args,**kwargs):
book_list=Book.objects.all()
# 文本类型,这个是和上面的连接有关,后面的参数context,HyperlinkedIdentityField,这个是设置了连接的时候,进行的操作
bs=BookSerializers(book_list,many=True,context={'request': request})
return Response(bs.data)


def post(self,request,*args,**kwargs):
print(request.data)
bs=BookSerializers(data=request.data,many=False)
if bs.is_valid():
print(bs.validated_data)
bs.save()
return Response(bs.data)
else:
return HttpResponse(bs.errors)


class BookDetailViewSet(APIView):
def get(self,request,pk):
book_obj=Book.objects.filter(pk=pk).first()
bs=BookSerializers(book_obj,context={'request': request})
return Response(bs.data)

def put(self,request,pk):
book_obj=Book.objects.filter(pk=pk).first()
bs=BookSerializers(book_obj,data=request.data,context={'request': request})
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return HttpResponse(bs.errors)


class PublishViewSet(APIView):
def get(self,request,*args,**kwargs):
publish_list=Publish.objects.all()
bs=PublshSerializers(publish_list,many=True,context={'request': request})
return Response(bs.data)


def post(self,request,*args,**kwargs):
bs=PublshSerializers(data=request.data,many=False)
if bs.is_valid():
# print(bs.validated_data)
bs.save()
return Response(bs.data)
else:
return HttpResponse(bs.errors)


class PublishDetailViewSet(APIView):
def get(self,request,pk):
publish_obj=Publish.objects.filter(pk=pk).first()
bs=PublshSerializers(publish_obj,context={'request': request})
return Response(bs.data)

def put(self,request,pk):
publish_obj=Publish.objects.filter(pk=pk).first()
bs=PublshSerializers(publish_obj,data=request.data,context={'request': request})
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return HttpResponse(bs.errors)

mixin类编写视图

继承mixins的ListModelMixin,CreateModelMixin等类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from rest_framework import mixins
from rest_framework import generics

class BookViewSet(mixins.ListModelMixin, # 查看继承类
mixins.CreateModelMixin, # 添加继承类
generics.GenericAPIView):

queryset = Book.objects.all()
serializer_class = BookSerializers

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 BookDetailViewSet(mixins.RetrieveModelMixin, # 查看单条继承类
mixins.UpdateModelMixin, # 更新单条继承类
mixins.DestroyModelMixin, # 删除单条继承类
generics.GenericAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializers

def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)

def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)

def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)

使用通用的基于类的视图

通过使用mixin类,我们使用更少的代码重写了这些视图,但我们还可以再进一步。REST框架提供了一组已经混合好(mixed-in)的通用视图,我们可以使用它来简化我们的views.py模块。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from rest_framework import mixins
from rest_framework import generics

class BookViewSet(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializers

class BookDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializers

class PublishViewSet(generics.ListCreateAPIView):
queryset = Publish.objects.all()
serializer_class = PublshSerializers

class PublishDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
queryset = Publish.objects.all()
serializer_class = PublshSerializers

viewsets.ModelViewSet

urls.py:

1
2
3
4
5
6
7
url(r'^books/$', views.BookViewSet.as_view({"get":"list","post":"create"}),name="book_list"),
url(r'^books/(?P<pk>\d+)$', views.BookViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
}),name="book_detail"),

views.py:

1
2
3
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializers

终极版

urls.py同上

views.py

1
2
3
4
5
from rest_framework.routers import DefaultRouter

router = DefaultRouter() # 实例化
router.register(r'school', views.SchoolView) # 注册
urlpatterns += router.urls # 在urlpatterns中添加

Django REST framework 视图
https://flepeng.github.io/021-Python-32-框架-Django-REST-framework-Django-REST-framework-视图/
作者
Lepeng
发布于
2021年8月18日
许可协议