【问题标题】:Accessing data from a custom serializer when being called by a nested serializer被嵌套序列化程序调用时从自定义序列化程序访问数据
【发布时间】:2015-10-10 17:47:59
【问题描述】:

我有一个调用其他序列化程序的序列化程序,而另一个序列化程序是一个自定义序列化程序,它覆盖了 .to_representation() 行为。如果我无法访问从视图发送到第一个序列化程序的数据,我应该如何从第一个序列化程序调用这个自定义序列化程序?

这是一个简单的例子:

class OtherSerializer(serializers.Serializer):
    def to_representation(self, obj):
        # ... can't get data

class NestedSerializer(serializers.Serializer):
    someotherfield = OtherSerializer(somedata, many=True)  # this fails because obviously can't read "somedata", how to get access to it?
    boolfield = BooleanField()

NestedSerializer(data={'someotherfield': somedata, 'boolfield': False})  # this somedata is the one I'm talking above

【问题讨论】:

    标签: django django-rest-framework django-serializer


    【解决方案1】:

    您可以尝试删除参数 somedata 吗?您的代码应如下所示:

    class NestedSerializer(serializers.Serializer):
        someotherfield = OtherSerializer(many=True)
        boolfield = BooleanField()
    

    我会假设键 'someotherfield' 指的是一个列表,否则你不需要 many=True。

    让我知道你的效果如何。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 2019-04-28
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多