I'm using django-rest-framework
and python-social-auth
in my Django project.
Here is the serializer class of UserSocialAuth
model in my project
class SocialAuthSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.CharField()
class Meta:
model = UserSocialAuth
fields = ('id', 'provider')
Then I want to an additional field UserSocialAuth.extra_data['login']
to above Serializer, the traditional way should be
class UserSocialAuth(AbstractUserSocialAuth):
def login:
return self.extra_data['login']
class SocialAuthSerializer(serializers.HyperlinkedModelSerializer):
login = serializers.CharField(source='login')
...
fields = ('id', 'provider', 'login')
The problem is that UserSocialAuth
is belong to python-social-auth
, I have to change the code of python-social-auth
app directly to add def login:
, so how can I add the additional field to the existing model UserSocialAuth
without touching the code of python-social-auth
.
I just find that I can use SerializerMethodField
here, no need to change the raw class UserSocialAuth
, just add one more field to the serializer like this:
class SocialAuthSerializer(serializers.HyperlinkedModelSerializer):
login = serializers.SerializerMethodField()
def get_login(self, obj):
return obj.extra_data['login']