[Fixed]-Merge two fields in one in a Django Rest Framework Serializer

33👍

You can create method in your serializer and show it by SerializerMethodField

class UserSerializer(serializers.ModelSerializer):
    full_name = serializers.SerializerMethodField()

    def get_full_name(self, obj):
        return '{} {}'.format(obj.first_name, obj.last_name) 

4👍

@Ivan semochkin’s answer works if the full_name is a read-only field but in my case I allow users to set full name so had to create a custom field and it works in both cases.

class FullNameField(serializers.Field):
    def to_representation(self, value):
        return value.get_full_name()

    def to_internal_value(self, full_name):
        fname, lname = full_name.split(' ')
        return {'first_name': fname, 'last_name': lname}

Now include this field in your serializer.

class UserSerializer(serializers.ModelSerializer):
    full_name = FullNameField(source='*')

Leave a comment