【发布时间】:2019-06-17 07:04:54
【问题描述】:
我正在尝试使用 ListSerializer,以便可以在 POST 的列表中创建/反序列化多个对象。我按照https://www.django-rest-framework.org/api-guide/serializers/#listserializer 的指南进行操作,但在访问端点时似乎遇到了这个错误。
assert self.child is not None, '``child`` is a required argument.'
python3.7/site-packages/rest_framework/serializers.py in __init__, line 592
我的序列化器如下:
class PredictionListSerializer(serializers.ListSerializer):
def update(self, instance, validated_data):
pass
def create(self, validated_data):
predictions = [Prediction(**item) for item in validated_data]
return Prediction.objects.bulk_create(predictions)
class NestedPredictionSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
# Nested Serializer
data = DataSerializer()
class Meta:
model = Prediction
list_serializer_class = PredictionListSerializer
fields = ('id', 'specimen_id', 'data' 'date_added',)
extra_kwargs = {
'slug': {'validators': []},
}
datatables_always_serialize = ('id',)
在 ListSerializer 的初始化中抛出了断言错误,但是,序列化器正在像这样在 ViewSet 中初始化。
class BulkPredictionViewSet(viewsets.ModelViewSet):
queryset = Prediction.objects.all()
serializer_class = PredictionListSerializer
有人熟悉这个问题吗?我想知道我缺乏对序列化程序初始化的控制(因为我使用的是 ViewSet)是否会影响这一点。如果我尝试将 NestedPredictionSerializer 传递到 ViewSet 我得到"Invalid data. Expected a dictionary, but got list."
编辑:
我能够覆盖我的 ViewSet 中的 get_serializer 方法以设置 many=True 并将序列化程序作为我的 NestedPredictionSerializer 传递,它可以识别 POST 上的列表。 Howeber,现在我收到错误When a serializer is passed a ``data`` keyword argument you must call ``.is_valid()`` before attempting to access the serialized ``.data`` representation.
You should either call ``.is_valid()`` first, or access ``.initial_data`` instead.
【问题讨论】:
标签: python django django-rest-framework