0

Is there any way to create serializer not model writable field from model two fields? Here is my Serializer

class UserProfileSerializer(serializers.ModelSerializer):
    full_name = ?
    class Meta:
        model = users.models.User
        fields = (
            'phone_number',
            'email',
            'city',
            'full_name'
        )

I want to connect firts_name and last_name into full_name

Sipan
  • 211
  • 3
  • 9

2 Answers2

2

You can use serializers.CharField() with write_only attribute;

class UserProfileSerializer(serializers.ModelSerializer):
    full_name = serializers.CharField(max_length=225, write_only=True,
                                      required=False, allow_null=True)
    class Meta:
        model = users.models.User
        fields = (
            'phone_number',
            'email',
            'city',
            'full_name'
        )

then you will be able to send json data like;

{
    "phone_number": "123456789",
    "email": "foo@bar.com",
    "city": "Foo",
    "full_name": "My Full Name"
}

and for getting that value after serializer.is_valid() method;

full_name = serializer.validated_data.get('full_name', '')
# full_name --> My Full Name
uedemir
  • 1,654
  • 1
  • 12
  • 21
  • In this case, it will not response full_name value on the get request. – Sipan Feb 08 '19 at 07:31
  • 2
    Then, I prefer you to use different serializers based on action. [Check this](https://stackoverflow.com/a/22922156/10170918) – uedemir Feb 08 '19 at 07:46
1

You can use a SerializerMethodField to construct the full_name from first_name + last_name:

from rest_framework import serializers

class UserProfileSerializer(serializers.ModelSerializer):
    full_name = serializers.SerializerMethodField()
    class Meta:
        model = users.models.User
        fields = (
            'phone_number',
            'email',
            'city',
            'full_name'
        )

    def get_full_name(self, instance):
        return "{} {}".format(instance.first_name, instance.last_name)
HuLu ViCa
  • 5,077
  • 10
  • 43
  • 93
  • How can you make it writable? Where would you put its value if there is not **full_name** field in the model? – HuLu ViCa Feb 12 '19 at 01:34