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
Top comments (2)
Thanks a lot, it's a very great aproach, this helped me a very much.
Hello, how do I remove the password from the user serializer? with depth=1 I am getting a response that include password.