Django rest framework writable nested serializer

a1k89

Andrei Koptev

Posted on March 26, 2021

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

💖 💪 🙅 🚩
a1k89
Andrei Koptev

Posted on March 26, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Choosing the Right Relational Database
undefined Choosing the Right Relational Database

November 29, 2024

Can a Solo Developer Build a SaaS App?
undefined Can a Solo Developer Build a SaaS App?

November 29, 2024

This Week In Python
python This Week In Python

November 29, 2024