如何使用Django RF修补Django的用户模型?

时间:2017-12-25 08:45:22

标签: python django django-models django-rest-framework django-serializer

我的UserProfile模型包含phoneprofile_photo以及Django默认用户模型的某些字段,如first_namelast_nameemail,我正在尝试更新其中一些字段。

models.py

class UserProfile(models.Model):
    user = models.ForeignKey(User, verbose_name="User")
    phone = models.CharField(max_length=16, verbose_name="Phone")
    profile_photo = models.ImageField(null=True, blank=True, upload_to=user_directory_path, verbose_name="Profile Photo")

serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'first_name', 'last_name', 'email')

class UserProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(partial=True)

    class Meta:
        model = UserProfile
        fields = '__all__'

    def create(self, validated_data):
        user_profile = UserProfile.objects.create(**validated_data)
        return user_profile

views.py

class UserProfileViewSet(viewsets.ModelViewSet):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
    authentication_classes = (TokenAuthentication,)

    @detail_route(methods=['PATCH'], url_path='update-partial')
    def user_profile_update_partial(self, request, pk=None):
        profile = UserProfile.objects.get(id=pk)
        serializer = self.get_serializer(profile, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)

如果我使用此profile_photo发送phonefirst_namelast_name@detail_route数据,我只能更新phone和profile_photo字段。当profile_photo数据未发送时,也会收到错误请求错误。

如何使用partial_update方法实施PATCH

1 个答案:

答案 0 :(得分:2)

class UserProfileViewSet(viewsets.ModelViewSet):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
    authentication_classes = (TokenAuthentication,)

    def partial_update(self, request, *args, **kwargs):
        profile = self.get_object()
        serializer = self.get_serializer(profile, data=request.data, partial=True)
        if serializer.is_valid():
            user_serializer = UserSerializer(profile.user, data=request.data, partial=True)
            if user_serializer.is_valid():
                user_serializer.save()
                serializer.save()
                return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
            else:
               return Response(data=user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(data=serializer.errors,status=status.HTTP_400_BAD_REQUEST)

Q1:如何实施PATCH方法?

A1:覆盖partial_update方法。

Q2:如何更新first_namelast_name

A2:使用另一个名为UserSerializer的序列化程序更新它。(如果需要更新密码,则需要使用make_password方法创建编码密码,然后再将原始密码保存到数据库中)