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"
}
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)
@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='*')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With