Django-Rest-Framework序列化器to_representation

7

我有一个带有SerializerMethodFieldModelSerializer。我想重写序列化器的to_representation方法以获得自定义输出,但我不知道如何访问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
2个回答

9

4
所以我做了以下事情:
def to_representation(self, instance):
        rep = super(MySerializer, self).to_representation(instance)
        duration = rep.pop('duration', '')
        return {
            # the rest
            'duration of cycle': duration,
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接