django rest框架序列化程序到_表示
我有一个带有django rest框架序列化程序到_表示,django,python-2.7,django-rest-framework,Django,Python 2.7,Django Rest Framework,我有一个带有SerializerMethodField的ModelSerializer。我想重写序列化程序的to_表示法以获得自定义输出,但我不知道如何访问SerializerMethodField: class MySerializer(serializers.ModelSerializer): duration = serializers.SerializerMethodField() def get_duration(self, obj): return
SerializerMethodField
的ModelSerializer
。我想重写序列化程序的to_表示法
以获得自定义输出,但我不知道如何访问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):
rep = super(MySerializer, self).to_representation(instance)
duration = rep.pop('duration', '')
return {
# the rest
'duration of cycle': duration,
}
def to_representation(self, instance):
rep = super(MySerializer, self).to_representation(instance)
duration = rep.pop('duration', '')
return {
# the rest
'duration of cycle': duration,
}