在DRF中,推荐使用类视图,因为类视图可以通过继承的方式把一些重复性的工作抽取出来,而使得代码更加简洁。当然如果你不想使用类视图,那么就用@api_view装饰器包裹一下就可以。
关于视图的逻辑,一共有10个
- 单查、群查
- 单增、群增
- 单删、群删
- 单全局改、单局部改
- 群全局改、群局部改(这2个用的非常少)
注意:如果我们做的删除操作是逻辑删除,单查群查的时候,需要先过滤数据,比如过滤掉被删除的,再返回给前台
class Students(APIView): def get_object(self, pk): try: return Student.objects.get(pk=pk) except Student.DoesNotExist: raise Http404 def get(self, request, *args, **kwargs): pk = kwargs.get('pk') # 有pk代表单查 if pk: student = self.get_object(pk) serializer = StudentModelSerializer(student) return Response({ "status": 0, "message": "成功", "results": serializer.data }) # 没有pk代表群查 else: queryset = Student.objects.all() serializer = StudentModelSerializer(instance=queryset, many=True) return Response({ "status": 0, "message": "成功", "results": serializer.data })
单增、群增操作
注意:单增操作的时候,看需求新增的是否是唯一的,如果是唯一,则需要判断数据已存在
def post(self, request, *args, **kwargs): request_data = request.data # 单增 if isinstance(request_data, dict): many = False # 群增 elif isinstance(request_data, list): many = True else: return Response({ "status": 1, "message": "数据有误", }) serializer = StudentModelSerializer(data=request_data, many=many) if serializer.is_valid(): serializer.save() return Response({ "status": 0, "message": "成功", "results": serializer.data }) return Response(serializer.errors, status=400)
单删、群删操作
注意:单删的时候,需要判断数据是否已经被删除
def delete(self, request, *args, **kwargs): # 单删 pk = kwargs.get("pk") if pk: pks = [pk] # 群删 else: pks = request.data.get('pks') queryset = Student.objects.filter(pk__in=pks) if queryset: queryset.delete() return Response({ "status": 0, "message": "删除成功", }) else: return Response({ "status": 1, "message": "删除失败", })
单局部改
单局部改instance=要被更新的对象,data=要更新的数据,partial=True,必填的字段都变为选填字段
def patch(self, request, *args, **kwargs): # 单局部改 pk = kwargs.get('pk') if pk: instance = Student.objects.filter(pk=pk).first() serializer = StudentModelSerializer(instance=instance, data=request.data, partial=True) if serializer.is_valid(raise_exception=True): serializer.save() return Response({ "status": 0, "message": "成功", "results": serializer.data }) else: return Response({ "status": 1, "message": "失败", })
单整体改
单整体改则将partial=False,partial默认为False
def put(self, request, *args, **kwargs): # 单整体改 pk = kwargs.get('pk') if pk: instance = Student.objects.filter(pk=pk).first() serializer = StudentModelSerializer(instance=instance, data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response({ "status": 0, "message": "成功", "results": serializer.data }) else: return Response({ "status": 1, "message": "失败", })
总结
APIView视图类就是做增删改查的操作,当然APIView中还继承了一些常用的属性,比如authentication_classes、permission_classes、throttle_classes等。