简体   繁体   中英

django-rest-framework serializer to_representation

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
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:

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,
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM