Created
April 10, 2020 07:51
-
-
Save coci/7c7fb5aeca75d00c7a310eed269c3682 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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