I have a ModelSerializer
with a SerializerMethodField
. I want to override the to_representation
method of the serializer to have custom output but I don't know how to access the SerializerMethodField
:
class MySerializer(serializers.ModelSerializer):
duration = serializers.SerializerMethodField()
def get_duration(self, obj):
return obj.time * 1000
def to_representation(self, instance):
return {
'name': instance.name,
'duration of cycle': # HOW TO ACCESS DURATION????
}
class Meta:
model = MyModel
So I did the following:
def to_representation(self, instance):
rep = super(MySerializer, self).to_representation(instance)
duration = rep.pop('duration', '')
return {
# the rest
'duration of cycle': duration,
}
def to_representation(self, instance):
duration = self.fields['duration']
duration_value = duration.to_representation(
duration.get_attribute(instance)
)
return {
'name': instance.name,
'duration of cycle': duration_value
}
ref:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With