Django-RESTful Api之基于类的视图
优点
- 把各种HTTP请求分离开,不用分支计算
- 增加了可读性
- 可以轻松的重复使用代码
修改视图
1 | from myApp.models import Student, Grade |
修改路由
1 | from django.conf.urls import url |
使用Mixins类
-
基本使用:
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
33from myApp.models import Student, Grade
from myApp.serializers import StudentSerializer
from rest_framework import mixins
from rest_framework import generics
# Create your views here.
# 只有一个父类能继承自APIView
class StudentsList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
# 通过get_queryset()和get_serializer()得到集合和序列化
queryset = Student.objects.all()
serializer_class = StudentSerializer
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 StudentDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
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) -
使用通用视图:
1
2
3
4
5
6
7
8
9
10
11
12
13
14from myApp.models import Student, Grade
from myApp.serializers import StudentSerializer
from rest_framework import generics
class StudentsList(generics.ListCreateAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
class StudentDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer