Skip to content

Instantly share code, notes, and snippets.

@coci
Created April 10, 2020 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coci/7c7fb5aeca75d00c7a310eed269c3682 to your computer and use it in GitHub Desktop.
Save coci/7c7fb5aeca75d00c7a310eed269c3682 to your computer and use it in GitHub Desktop.
# in this seriliazer : 'user' is forignkey to customuser
# i need add user name and pk instead of pk only
class LandSerializer(serializers.ModelSerializer):
points = PointSerializer(many=True, read_only=True)
class Meta:
model = Land
fields = ('pk', 'user', 'name', 'create_time', 'points')
def to_representation(self, instance):
# this will add user full_name filed to user objects
response = super().to_representation(instance)
response['user'] = {'pk': 0, 'full_name': ''}
response['user']['pk'] = UserSerializer(instance=instance.user).data['pk']
response['user']['full_name'] = UserSerializer(instance=instance.user).data['full_name']
return response
"""
this is how above code will response :
{
"pk": 48,
"user": { # now user have pk and its full_name field
"pk": 1,
"full_name": "soroush safari"
},
"name": "so",
"create_time": "2020-04-09T12:04:29.066928Z"
}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment