Skip to content Skip to sidebar Skip to footer

Confusion On Which Serializer To Use To Update User Profile

I have a profile model for user to update. I want to have a rest api for that. I have a profile model which is too big than usual. I am working to update the user profile but I am

Solution 1:

It's a standard to use the PUT request method for updating in your current code and situation it is better to use the ProfileSerializer since it has more fields. Also, the way I see it you only have three fields in the User object that can be changed and those three fields I assume is rarely changed.

views.py

defput(self, request, *args, **kwargs):
    """
    update a profile
    """
    data = request.data
    print data
    try:
        profile = Profile.objects.get(token=data.get('token'))
    except:
        return Response(status=status.HTTP_400_BAD_REQUEST)
    serializer = self.serializer_class(profile, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status.HTTP_200_OK)

    else:
        return Response(serializer.errors,
                        status.HTTP_400_BAD_REQUEST)

serializers.py

classProfileSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(read_only=True)

    classMeta:
        model = Profile
        fields = ('user', 'height', 'weight', 'token')

    defto_internal_value(self, data):
        first_name = data.pop('first_name', None)
        last_name = data.pop('last_name', None)
        data = super(ProfileSerializer, self).to_internal_value(data)
        data['first_name'] = first_name
        data['last_name'] = last_name
        return data

    defupdate(self, instance, validated_data):
        first_name = validated_data.pop('first_name', None)
        last_name = validated_data.pop('last_name', None)
        user_inst_fields = {}
        if first_name:
            user_inst_fields['first_name'] = first_name
        if last_name:
            user_inst_fields['last_name'] = last_name
        if user_inst_fields:
            User.objects.update_or_create(pk=instance.user.id,
                                          defaults=user_inst_fields)
        profile, created = Profile.objects.update_or_create(
            token=instance.token, defaults=validated_data)
        return profile

Simply just set the user to read only for it to avoid validation

Post a Comment for "Confusion On Which Serializer To Use To Update User Profile"