Django rest framework writable nested serializer
Andrei Koptev
Posted on March 26, 2021
Prepare
- You have Django and Django rest framework
- You have
User
withProfile
asone-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'
]
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)
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
💖 💪 🙅 🚩
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.