Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two fields in one in a Django Rest Framework Serializer

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"
}
like image 270
Rafael Gil Avatar asked Sep 08 '16 09:09

Rafael Gil


2 Answers

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) 
like image 54
Ivan Semochkin Avatar answered Nov 01 '22 02:11

Ivan Semochkin


@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='*')
like image 37
Premkumar chalmeti Avatar answered Nov 01 '22 00:11

Premkumar chalmeti