0

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?

dfrankow
  • 20,191
  • 41
  • 152
  • 214
  • `SerializerMethodField` is a read-only field. So it is used only during serialization. You can use extra context to pass in the request to the serializer and use it there. – Dineshs91 Feb 23 '21 at 07:33

2 Answers2

2

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})
tim-mccurrach
  • 6,395
  • 4
  • 23
  • 41
0

class MySerializer(serializers.Serializer): my_field = serializers.SerializerMethodField()

def to_represention(self,instance):
       data=super().to_representation(instance)
       data["user"]="new filed"
       return data