Django休息框架嵌套序列化器部分更新

zer*_*g . 5 python django rest frameworks

串行:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('foo', 'bar')


class UserSerializer(serializers.ModelSerializer):
    userprofile = ProfileSerializer(partial=True)

    class Meta:
        model = User
        fields = ('username', 'password', 'email', 'userprofile')

    def create(self, validated_data):
        profile_data = validated_data.pop('userprofile')
        user = User.objects.create(**validated_data)
        UserProfile.objects.create(user=user, **profile_data)

        return user

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('userprofile')
        profile = instance.userprofile

        instance.username = validated_data.get('username', instance.username)
        instance.email = validated_data.get('email', instance.email)
        instance.save()

        profile.foo = profile_data.get('foo', profile.foo)
        profile.bar = profile_data.get('bar', profile.bar)
        profile.save()

        return instance
Run Code Online (Sandbox Code Playgroud)

视图:

class UsersViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
Run Code Online (Sandbox Code Playgroud)

创建和更新都工作正常,问题是部分更新.django用户模型具有所需的用户名,我想使其成为可选项.有没有办法为这种情况启用部分更新?

例如,我想用PUT更新"foo".

sem*_*lon 6

默认情况下,PUT应提供所有必需的参数.但PATCH不是.因此,只要您使用PATCH而不是PUT就可以了,您根本不需要更改代码.

我个人认为这有点奇怪,PUT需要所有不是可选的参数,但会单独留下可选参数.因此,您可以编辑可选参数,同时保留其他可选参数但不能对必需参数执行相同操作(我的意思是您显然可以只提供现有值,但如果在编辑时它们发生了变化则会被搞砸并强制更改它们背部).PATCH对我来说更有意义.您提供的任何参数都将被更改,而您提供的任何参数都不会更改.IMO PUT应该清除任何未提供的可选参数,以便它是一个真正的替换,而不是简单的替换需要和更新(PUT)可选.