[Django]-Django REST Framework: Nested Serializers not appearing

3👍

You don’t need to create NameSerializer serializer. Create a method field in UserSerializer for name field such as:

class UserSerializer(serializers.ModelSerializer):

    userName = serializers.EmailField(source='email')
    name = serializers.SerializerMethodField()

    class Meta:
        model = Person
        fields = ('id', 'userName', 'name')

    def get_name(self, obj):
        name = {
            'familyName': obj.first_name,
            'givenName': obj.last_name,
            'formatted': obj.first_name + ' ' + obj.last_name
        }
        return name

It will give your desired result.

0👍

Maybe try using SerializerMethodField:
Something like this:

class UserSerializer(serializers.ModelSerializer):

    userName = serializers.EmailField(source='email')
    name = serializers.SerializerMethodField()

    class Meta:
        model = Person
        fields = ('id', 'userName', 'name')

    def get_name(self, obj):
        return {
            'familyName': obj.first_name,
            'givenName': obj.last_name,
            'formatted': obj.first_name + ' ' + obj.last_name
        }

0👍

This might help you:

class UserSerializer(serializers.ModelSerializer):
name = NameSerializer()
userName = serializers.EmailField(source='email')

     class Meta:
         model = Person
         fields = ('id', 'userName', 'name')

If the items should be a list, then only you need to pass many=True.

Leave a comment