[英]django-rest-framework serializer to_representation
I have a ModelSerializer
with a SerializerMethodField
. 我有一个带有SerializerMethodField
的ModelSerializer
。 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
: 我想覆盖序列化程序的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
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,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.