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

问题描述 投票:0回答:1

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

models.朋友

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")

serialize认识.朋友

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.朋友

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_photophonefirst_namelast_name数据与此@detail_route我只能更新phone和profile_photo字段。当profile_photo数据不发送时也会收到错误请求错误。

如何用partial_update方法实现PATCH

python django django-models django-rest-framework django-serializer
1个回答
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方法创建编码密码,然后再将原始密码保存到数据库)

© www.soinside.com 2019 - 2024. All rights reserved.