django-rest 重写ModelViewSet中的create方法

实现基本功能,网页上post一张图片(字段name,image),存入re_photo表,使用字段name在worker表(字段name,number,gender,job,photo)中做查询,匹配出具有相同name的两张图片做识别

class RecognitionViewSet(viewsets.ModelViewSet):
    queryset = re_photo.objects.all()        #上传图片界面
    serializer_class = PhotoSerializer
    permission_classes(IsAuthenticated,)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)   #上传的图片序列化
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        name_re_photo =serializer.data['name']     #提取字段name
        object_worker = worker.objects.filter(name=name_re_photo)  # worker中查询是否匹配name_re_photo
        if len(object_worker)!=0:                      #研究是否有匹配的name
            serializer2 = WorkerSerializer(object_worker, many=True)
            serializer2.data[0]['photo']='http://127.0.0.1:8000/api/recognition/'+serializer2.data[0]['photo']
            result = test.getresult(36)     #人脸识别函数,先构造简单函数替代

            return Response({
            "status": status.HTTP_200_OK,
            "message": 'Working right.',
            "tag": 'pass',
            "data": serializer2.data})    #返回worker中匹配的图片地址
        else:
            return Response({
            "status": status.HTTP_200_OK,
            "message": 'Working right.',
            "tag": 'no pass',
            "data": [ ]})

create方法的原始代码如下  地址 http://www.cdrf.co/3.1/rest_framework.viewsets/ModelViewSet.html

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data) # request.data为上传的信息,经输出实验可知serializer.data是一个字典,可提取出name
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
重写方法,首先要明确,原方法中使用数据的数据结构,通过输出实验来验证。之后,将原方法的数据向我们所需要的数据进行转换。

你可能感兴趣的:(django-rest 重写ModelViewSet中的create方法)