条件串行器类的请求方法

时间:2019-04-16 11:49:11

标签: python django django-rest-framework

我正在创建一个用于创建或更新的api。因此,如果auth用户不存在,将创建该用户,如果存在,则将检查配置文件属性中的任何更新。因此,我使用了PATCH方法,可以在其中创建和更新。我想创建两个序列化程序类,一个为EmployeeCreate,另一个为EmployeeUpdate。因为补丁请求将保存请求数据,所以我可以找到用户是否已经存在的天气,然后我想在PATCH方法中选择序列化器类。我什至不能使用get_serializer_class(),因为我必须在所有方法之前定义序列化器类。

视图中

class AddEMPLOYEE(AllCreateErrorPatch, UpdateAPIView):

    queryset = UserProfile.objects.all()
    authentication_classes = [TokenAuthentication, ]
    permission_classes = [IsAdminUser]
    serializer_class = None

    def patch(self, request, *args, **kwargs):
        print(self.get_serializer_class())
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid():
            return self.response_error(serializer.errors)

        req_data = serializer.validated_data
        if User.objects.filter(email=request.data['email']).count()==0:
            serializer_class = EmployeeCreate
            user_fields = ["email", "first_name", "last_name", "password"]

            user_data = {field: req_data[field] for field in user_fields}
            for field in user_fields:
                del req_data[field]

            user_serializer = UserSerializer(data=user_data)
            if not user_serializer.is_valid():
                return self.response_error(user_serializer.errors)
            user_serializer.save()

            req_data['user'] = user_serializer.data["id"]
         else:
            serilaizer_class = EmployeeUpdate

        user_profile = UserProfile.objects.get(user=User.objects.get(email=request.data['email']))
        user_profile_serializer = UserProfileSerializer(user_profile, data=req_data, partial=True)
        if not user_profile_serializer.is_valid():
            return self.response_error(user_profile_serializer.errors)

        user_profile_serializer.save()

        resp = user_profile_serializer.data
        # resp.update(user_serializer.data)
        del resp["user"]
        return Response(resp)

在序列化器中

EmployeeEmployee(UserProfileSerializer,UserSerializer)类:

class Meta:
    model = UserProfile
    exclude = ("user", )

Class EmployeeUpdate(UserProfileSerializer,UserSerializer):

class Meta:
    model = UserProfile
    fields = ("mobile",)

我想要一种技术,通过该技术我们可以在请求方法内进行某种条件的序列化程序选择

1 个答案:

答案 0 :(得分:0)

理想情况下,您不应该将create和patch混合在一起,但是必须这样做:

class AddEMPLOYEE(AllCreateErrorPatch, UpdateAPIView):

    queryset = UserProfile.objects.all()
    authentication_classes = [TokenAuthentication, ]
    permission_classes = [IsAdminUser]
    # you do not need to define the serializer class

    def patch(self, request, *args, **kwargs):
        req_data = request.data
        email = req_data.get('email')

        if User.objects.filter(email=email).exists(): # this is faster
            # do whatever on patch
            if EmployeeUpdate(data=req_data).is_valid():
                return # positive response
            return # negative response
         else:
            # do whatever on create
            if EmployeeCreate(data=req_data).is_valid():
                return # positive response
            return # negative response

从本质上讲,尽管强烈建议,但您不必使用django自己的视图预设,例如serializer class。我强烈建议不要混淆补丁程序的逻辑,而只是出于理智而创建,但这在技术上是可行的。