尝试更新用户时,会显示以下消息:“具有此用户名的用户已存在”
我有一个标准的Django用户模型,我有另一个扩展的配置文件模板。
如何更新此数据,包括用户个人资料。
谢谢。
模型
class Profile(User):
nome_empresa = models.CharField(max_length=200)
cnpj = models.CharField(max_length=15)
def __str__(self):
return self.nome_empresa
串行
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('nome_empresa', 'cnpj')
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'profile')
查看
class usuario(APIView):
def patch(self, request, format=None):
user = UserSerializer(data=request.data)
if user.is_valid():
user.update(instance=request.user)
return Response(HTTP_200_OK)
return Response(user.errors)
答案 0 :(得分:2)
django-rest-framework默认不更新嵌套序列化程序。要更新配置文件对象,您需要覆盖序列化程序的更新方法。
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
def update(self, instance, validated_data):
'''
Override update method because we need to update
nested serializer for profile
'''
if validated_data.get('profile'):
profile_data = validated_data.get('profile')
profile_serializer = ProfileSerializer(data=profile_data)
if profile_serializer.is_valid():
profile = profile_serializer.update(instance=instance.profile)
validated_data['profile'] = profile
return super(UserSerializer, self).update(instance, validated_data)
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'profile')