有关使用的文档to_representation
有点短。该方法用于Django Rest Framework 3.0+
更改数据在 API 中的表示形式。
这是文档链接:
http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior
这是我当前的代码:
from django.forms.models import model_to_dict
class PersonListSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('foo', 'bar',)
def to_representation(self, instance):
return model_to_dict(instance)
当我执行此代码时,它返回模型中的所有字段,而不是我在上面指定的字段class Meta: fields
.
是否可以参考一下class Meta: fields
内to_representation
method?
DRF's ModelSerializer
已经有了处理这个问题的所有逻辑。在你的情况下,你甚至不需要定制to_representation
。如果您需要自定义它,我建议首先调用 super,然后自定义输出:
class PersonListSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('foo', 'bar',)
def to_representation(self, instance):
data = super(PersonListSerializer, self).to_representation(instance)
data.update(...)
return data
附:如果你有兴趣知道它是如何工作的,那么魔法实际上并不会发生在ModelSerializer.to_representation
。事实上,它甚至没有实现该方法。其定期实施Serializer https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L438-L458。 Django 模型的所有魔力实际上都发生在get_fields https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L867哪个调用get_field_names https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L936然后考虑Meta.fields
参数...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)