Django Rest Framework中的to_representation()可以访问正常字段 [英] Can to_representation() in Django Rest Framework access the normal fields

查看:3104
本文介绍了Django Rest Framework中的to_representation()可以访问正常字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 to_representation 的文档有些短。此方法由 Django Rest Framework 3.0 + 用于更改API中数据的表示。

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.

此处'文档链接:

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)

当我执行此代码时,它会返回模型中的所有字段,而不是以上指定的字段类Meta:fields

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.

可以在 to_representation 类Meta:fields $ c>方法?

Is it possible to reference the class Meta: fields within the to_representation method?

推荐答案

DRF的 ModelSerializer 已经具有所有逻辑来处理。在您的情况下,您甚至不需要自定义 to_representation 。如果你需要定制它,我建议先调用super,然后自定义输出:

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:

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






PS如果你有兴趣知道它是如何工作的,魔术实际上并不会发生在 ModelSerializer.to_representation 中。事实上,它甚至没有实现这种方法。它通常在 串行 。 Django的所有魔力都会发生在 get_fields ,调用 get_field_names ,然后再考虑 Meta.fields 参数...


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...

这篇关于Django Rest Framework中的to_representation()可以访问正常字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆