​ListSerializer类​​  文档注解

​ListSerializer​​类提供了序列化和一次验证多个对象的行为。您通常不需要​​ListSerializer​​​直接使用,而应该​​many=True​​在实例化序列化程序时简单地通过。

class TrackListSerializer(serializers.ListSerializer):
def create(self, validated_data):
#validated_data会返回所有请求数组,而不是单个对象
print(validated_data)
books = [Track(**item) for item in validated_data]
return Track.objects.bulk_create(books)
def to_internal_value(self, data):
print('to_internal_value',data)
return data.get('data')
class TrackSerializer(serializers.ModelSerializer):
# album = AlbumField(queryset=Album.objects.all())

class AlbumSerilaizer(serializers.ModelSerializer):
class Meta:
model = Album
fields = "__all__"
album = AlbumSerilaizer(many=False,read_only=True)
class Meta:
model = Track
fields = "__all__"
list_serializer_class = TrackListSerializer
class RouterViewSet(viewsets.ModelViewSet):
authentication_classes = ()
serializer_class = TrackSerializer
queryset = Track.objects.all()

def create(self, request, *args, **kwargs):
data = request.data.get('data')

if isinstance(data,dict):
return super().create(request,*args,**kwargs)

elif isinstance(data,list):
# 当many=True时,TrackSerializer会直接调用list_serializer_class属性
ser=TrackSerializer(many=True,data=request.data)
if ser.is_valid():
ser.save()
return Response(ser.data)