gpt4 book ai didi

python - Django rest framework 嵌套序列化器部分更新

转载 作者:太空狗 更新时间:2023-10-30 00:31:56 24 4
gpt4 key购买 nike

序列化器:

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

查看:

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

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

例如,我只想用 PUT 更新“foo”。

最佳答案

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

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

关于python - Django rest framework 嵌套序列化器部分更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27553596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com