[Django]-Write an explicit `.update()` method for serializer

4๐Ÿ‘

I solved this by override update method in serializer

class AccountProfileSerializer(serializers.ModelSerializer):
    gender = serializers.CharField(source='accountprofile.gender')
    phone = serializers.CharField(source='accountprofile.phone')
    location = serializers.CharField(source='accountprofile.location')
    birth_date = serializers.CharField(source='accountprofile.birth_date')
    biodata = serializers.CharField(source='accountprofile.biodata')

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'gender',
                  'phone', 'location', 'birth_date', 'biodata')

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('accountprofile')
        profile = instance.accountprofile

        # * User Info
        instance.first_name = validated_data.get(
            'first_name', instance.first_name)
        instance.last_name = validated_data.get(
            'last_name', instance.last_name)
        instance.email = validated_data.get(
            'email', instance.email)
        instance.save()

        # * AccountProfile Info
        profile.gender = profile_data.get(
            'gender', profile.gender)
        profile.phone = profile_data.get(
            'phone', profile.phone)
        profile.location = profile_data.get(
            'location', profile.location)
        profile.birth_date = profile_data.get(
            'birth_date', profile.birth_date)
        profile.biodata = profile_data.get(
            'biodata', profile.biodata)
        profile.save()

        return instance
๐Ÿ‘คuser13094622

Leave a comment