15

I am using Django Rest Framework authentication system which comes with a default user table. In that table it splits first and last name in two different char fields.

Is it possible to join these two fields in a serializer? Something like this:

class UserSerializer(serializers.ModelSerializer):
    full_name = serializers.CharField(source='user.first_name' + ' ' + 'user.last_name')

So that I would get the following response:

{
    full_name: "firs_name last_name"
}

2 Answers 2

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) 
1
  • 1
    Is it possible to add two or more payloads into one with this approach? Commented Oct 21, 2021 at 13:15
5

@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='*')
1
  • 2
    This reponse could be improved because 1) ret is not defined 2) value.get_full_name() - might be mention which method is that (I guess model method) I gave +1 anyway because it was helpful and works for me (read + set value) ;) Commented Sep 24, 2021 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.