如何更新Django Rest User属性?

时间:2016-09-01 21:19:03

标签: python django rest django-rest-framework

我有这个型号:

class UserProfile(models.Model):

    user = models.OneToOneField(User, related_name='profile')
    stuff = models.TextField(default='')

User.profile = property(UserProfile)

使用此序列化程序:

class UserProfileSerializer(UserSerializer):

    stuff = serializers.SerializerMethodField()

    def get_stuff(self, obj):
        return obj.profile.stuff

    def update(self, instance, validated_data):
        instance.profile.stuff = validated_data.get('stuff', instance.profile.stuff)
        instance.save()
        return instance

使用此终点:

class UpdateUserProfile(UpdateAPIView):

    model = UserProfile
    serializer_class = UserProfileSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_object(self):
        return self.request.user

当我调用HTTP / PUT来更新我的东西时,它不会更新。我不知道为什么。

1 个答案:

答案 0 :(得分:0)

如果您的更新方法正在执行,并且您在方法中获得了instance.profile。问题发生在

instance.profile.stuff = validated_data.get('stuff', instance.profile.stuff)
instance.save()

您需要更新配置文件实例。

instance.profile.stuff = validated_data.get('stuff', instance.profile.stuff)
instance.profile.save()

“instance.profile.save()”将更新您的个人资料实例。