This question asks how to add an additional field to ModelSerializer.
This answer says you can add a SerializerMethodField
. But, how to implement a method field if the value of the call depends on some other parameter, like the request?
This question asks how to add an additional field to ModelSerializer.
This answer says you can add a SerializerMethodField
. But, how to implement a method field if the value of the call depends on some other parameter, like the request?
You can use the serializers context (see docs) for this
class MySerializer(serializers.Serializer):
my_field = serializers.SerializerMethodField()
def get_my_field(self, obj):
request = self.context['request']
# do something with request and obj
Then when you initialize the serializer be sure to pass in the request object in the context e.g:
serializer = MySerializer(myObject, context={'request': request})
class MySerializer(serializers.Serializer): my_field = serializers.SerializerMethodField()
def to_represention(self,instance):
data=super().to_representation(instance)
data["user"]="new filed"
return data