Django RestFramework Serializer request.data with array object

时间:2017-10-10 21:56:41

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

我有这种情况,我通过POST收到了这个数据:

{'fields':[{'key':'comment', 'value':'something', 'data_type':'string'},
           {'key':'days', 'value':'2', 'data_type':'int'}]}

我的序列化程序

class FieldSerializer(serializers.Serializer):
    value = serializers.CharField(max_length=200)
    data_type = serializers.CharField(max_length=200)
    key = serializers.CharField(max_length=200)


class FieldsSerializer(serializers.Serializer):
    fields = FieldSerializer(many=True)

在我看来,将request.data传递给FieldsSerializer()

serializer = FieldsSerializer(data=request.data)
serializer.is_valid()
raise Exception(serializer.data, serializer.errors)

输出:

  

例外:(ReturnDict([('fields',[])]),ReturnDict())

我使用版本Django == 1.8.15和djangorestframework == 3.0

1 个答案:

答案 0 :(得分:0)

您拥有FieldsSerializer的单个数据,因此您只需在初始化序列化程序时删除many=True

serializer = FieldsSerializer(data=request.data)
#                                          ^^^^^^

或作为通用解决方案

many = isinstance(request.data, list)
serializer = FieldsSerializer(data=request.data, many=many)