ListSerializer使用

上代码

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

viewset

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)
请求参数

你可能感兴趣的:(ListSerializer使用)