DEV Community

Andrei Koptev
Andrei Koptev

Posted on

Django rest framework writable nested serializer

Prepare

  • You have Django and Django rest framework
  • You have User with Profile as one-to-one
  • You have serializers:
class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = [
            'experience',
            'rate',
        ]

class UserSerializer(serializers.ModelSerializer):
    avatar = ImageBase64Field(required=False)
    profile = UserProfileSerializer(required=False)

    class Meta:
        model = User
        fields = [
            'uid',
            'first_name',
            'last_name',
            'profile'
        ]

Enter fullscreen mode Exit fullscreen mode

Problems

  • You want to update experience field in user profile

Solution

Add update method in your UserSerializer class.

class UserSerializer(serializers.ModelSerializer):
    ...

    def update(self, instance, validated_data):
        if validated_data.get('profile'):
            profile_data = validated_data.get('profile')
            profile_serializer = UserProfileSerializer(data=profile_data)

            if profile_serializer.is_valid():
                profile = profile_serializer.update(instance=instance.profile,
                                                    validated_data=profile_serializer.validated_data)
                validated_data['profile'] = profile

        return super().update(instance, validated_data)

Enter fullscreen mode Exit fullscreen mode

Now, with user data we may to send profile data and update our user profile.

Conclusion

  • Now we may to update user profile easily in one request

Thanks for reading

Top comments (2)

Collapse
 
edderleonardo profile image
archi ✖

Thanks a lot, it's a very great aproach, this helped me a very much.

Collapse
 
isaachatilima profile image
Isaac Hatilima

Hello, how do I remove the password from the user serializer? with depth=1 I am getting a response that include password.