The docs on using to_representation
is somewhat short. This method is used by Django Rest Framework 3.0+
to change the representation of your data in an API.
关于使用to_representation的文档有点简短。 Django Rest Framework 3.0+使用此方法更改API中数据的表示形式。
Here' the documentation link:
这里是文档链接:
Here is my current code:
这是我目前的代码:
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)
When I do this code, it returns all fields in the model instead of the fields that I have specified above in class Meta: fields
.
当我执行此代码时,它返回模型中的所有字段,而不是我在类Meta:fields中指定的字段。
Is it possible to reference the class Meta: fields
within the to_representation
method?
是否可以在to_representation方法中引用类Meta:字段?
22
DRF's ModelSerializer
already has all the logic to handle that. In your case you shouldn't even need to customize to_representation
. If you need to customize it, I would recommend to first call super and then customize the output:
DRF的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
P.S. if you are interested to know how it works, the magic actually does not happen in ModelSerializer.to_representation
. As a matter of fact, it does not even implement that method. Its implemented on regular Serializer
. All the magic with Django models actually happens in get_fields
which calls get_field_names
which then considers the Meta.fields
parameters...
附:如果你有兴趣知道它是如何工作的,那么魔法实际上并不会发生在ModelSerializer.to_representation中。事实上,它甚至没有实现这种方法。它在常规的Serializer上实现。 Django模型的所有魔法实际上都发生在get_fields中,它调用get_field_names然后考虑Meta.fields参数......
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/08/04/cc2642d621d9308ea4139fc1f98edd86.html。