DEV Community

Andrei Koptev
Andrei Koptev

Posted on

Django rest framework writable nested serializer


  • 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 = [

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

    class Meta:
        model = User
        fields = [

Enter fullscreen mode Exit fullscreen mode


  • You want to update experience field in user profile


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'] = 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.


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

Thanks for reading

Top comments (2)

edderleonardo profile image
archi ✖

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

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.