[Answered ]-Drf: Add a non-model field in Serializer

1👍

You can do something like this with a SerializerMethodField

class GetMessageSerializer(serializers.ModelSerializer):
    sender = SimpleUserSerializer()
    receiver = SimpleUserSerializer()
    name = serializers.SerializerMethodField() #this field will call the method "get_name" in this serializer for value.

    def get_name(self, obj):
        user = self.context['request'].user
        if user==obj.receiver:
            return obj.sender.first_name
        return obj.receiver.first_name

    class Meta:
        model = Message
        fields = ('sender','receiver','body','date','seen', 'name') #added name here

Leave a comment