将许多序列化程序添加到嵌套的序列化器字段中

时间:2016-06-04 12:05:33

标签: python django python-3.x django-rest-framework

serializers.py

class BusOncomingSerializer(serializers.Serializer):
    idn = serializers.IntegerField(read_only=True)
    stops_left = serializers.IntegerField(read_only=True)


class StopOncomingSerialier(serializers.Serializer):
    idn = serializers.IntegerField(read_only=True)
    buses = BusOncomingSerializer(many=True)

我的序列化程序实例在列表中有效,如下所示:

buses_serializers = [bus1, bus2, bus3]
# busX means instance of BusOncomingSerializer and they are valid.

我正在尝试将这些BusOncomingSerializer实例添加到单个StopOncomingSerializer实例中:

serializer = serializers.StopOncomingSerializers(data={"idn": 1, "buses": buses_serializers})

我跑is_valid()。然而,它提出了:

  

TypeError: BusOncomingSerializer(data = {'idn':285,'stops_left':7}):idn = IntegerField(read_only = True)stops_left = IntegerField(read_only = True)不是JSON序列化

如果我没有用列表添加序列化程序实例,还有其他方法吗?

环境

  • python 3.5.1
  • django 1.9.5
  • django-rest-framework 3.3.3

1 个答案:

答案 0 :(得分:3)

您将数据错误地传递给StopOncomingSerializer。您应该将值作为字典列表传递,而不是传递bus个实例。

示例数据格式:

{
    'idn': 7, 
    'buses': [
        {'idn':3, 'stops_left': 3}, 
        {'idn': 4, 'stops_left':6}
    ]
}

在Python Shell上:

In [5]: data = {'idn': 7, 'buses': [{'idn':3, 'stops_left': 3}, {'idn': 4, 'stops_left':6}]}

In [6]: s1 = StopOncomingSerialier(data=data)

In [7]: s1.is_valid()
Out[7]: True