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
}
- [Django]-How do I successfully pass variables to my python social auth pipeline?
- [Django]-Django/django-tables2 html table on row click to edit form
- [Django]-Getting data from an Excel sheet
- [Django]-HAProxy load balancer in front of Django instances
- [Django]-Can't parse a static JSON file in Django 1.8
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
.
Source:stackexchange.com