问题描述
我正在努力理解 ListField
和 DictField
。我想使用它作为串行器上的一个字段。我有一个 ListField
,它可能包含许多 DictField
。我试图编写一个串行器如下:
I am having struggle with understanding ListField
and DictField
. I want to use it as a field on a serializer. I have a ListField
which probably will contain many DictField
. I tried to write a serializer as below:
class StopOncomingSerialier(serializers.Serializer):
idn = serializers.IntegerField(read_only=True)
buses = serializers.ListField(
child=serializers.DictField(
idn=serializers.IntegerField(read_only=True),
stops_left=serializers.IntegerField(read_only=True)
),
read_only=True
)
我知道这是没有意义的,因为文档说 DictField
和 ListField
take 孩子
作为参数。所以,上面的代码自然地提出了错误:
I know, it does not make sense, since the documentation says DictField
and ListField
take child
as argument. And so, the code above naturally raised error:
期望的输出
Desired Output
{
"idn": 1,
"buses": [
{"idn": 11, "stops_left": 4},
{"idn": 12, "stops_left": 15}
]
}
如何实现? 公交车
是一个列表,可能包含与我想要的一样多的元素。
How to achieve this? buses
is a list and might contain as many elements as I want.
- python 3.5.1
- django 1.9.6
- django-rest-framework 3.3.3
推荐答案
我想,而不是这样做,你应该使用嵌套的序列化程序。
I think instead of doing that, you should use nested serializers.
创建一个 BusSerializer
有字段 idn
和 stops_left
。然后在 StopOncomingSerializer
中将此串行器包含为总线
字段与 many = True
参数来处理多个总线
数据。
Create a BusSerializer
having fields idn
and stops_left
. Then include this serializer in your StopOncomingSerializer
as buses
field with many=True
argument to handle multiple buses
data.
class BusSerializer(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 = BusSerializer(many=True)
这篇关于Django Rest框架ListField和DictField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!