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序列化
如果我没有用列表添加序列化程序实例,还有其他方法吗?
答案 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