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?

1
  • 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. Commented Feb 23, 2021 at 7:33

2 Answers 2

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})
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.