我正在尝试使用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传递给NestedPredictionSerializer,以识别POST上的列表。豪伯,现在我收到错误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.
答案 0 :(得分:0)
仅将many=True
用于create
action:
class BulkPredictionViewSet(viewsets.ModelViewSet):
queryset = Prediction.objects.all()
serializer_class = NestedPredictionSerializer
def get_serializer(self, *args, **kwargs):
serializer_class = self.get_serializer_class()
kwargs['context'] = self.get_serializer_context()
if if self.action == 'create':
kwargs['many'] = True
return serializer_class(*args, **kwargs)
您不需要使用PredictionListSerializer
,因为many=True
会自动创建ListSerializer
。
答案 1 :(得分:0)
当以下阅读建议结合此答案时,我能够同时执行POST和GET:https://stackoverflow.com/a/45651309/3439441
我覆盖的ViewSet.get_serializer
现在看起来像这样:
def get_serializer(self, *args, **kwargs):
if self.request.method.lower() == 'post':
data = kwargs.get('data')
kwargs['many'] = isinstance(data, list)
return super(BulkPredictionViewSet, self).get_serializer(*args, **kwargs)