【问题标题】:Can to_representation() in Django Rest Framework access the normal fieldsDjango Rest Framework 中的 to_representation() 可以访问普通字段吗
【发布时间】:2015-10-27 12:19:52
【问题描述】:

使用to_representation 的文档有点短。 Django Rest Framework 3.0+ 使用此方法更改数据在 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)

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

是否可以在to_representation 方法中引用class Meta: fields

【问题讨论】:

标签: python django django-rest-framework


【解决方案1】:

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

附:如果您有兴趣知道它是如何工作的,那么ModelSerializer.to_representation 中实际上并没有发生魔法。事实上,它甚至没有实现该方法。它在常规Serializer 上实施。 Django 模型的所有魔力实际上都发生在 get_fields 中,它调用 get_field_names,然后考虑 Meta.fields 参数...

【讨论】:

  • 嗨,有什么方法可以在这里动态传递序列化器名称:- data = super(PersonListSerializer, self).to_representation(instance)
猜你喜欢
  • 2015-06-29
  • 1970-01-01
  • 2016-03-15
  • 2021-12-24
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 2021-03-06
  • 2015-09-14
相关资源
最近更新 更多