我有ModelSerializer
SerializerMethodField
。我想覆盖序列化程序的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
答案 0 :(得分:5)
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:
答案 1 :(得分:1)
所以我做了以下事情:
def to_representation(self, instance):
rep = super(MySerializer, self).to_representation(instance)
duration = rep.pop('duration', '')
return {
# the rest
'duration of cycle': duration,
}