我应该怎么做才能在 django rest 框架的代码中 post 多个内容?

what should i do to be able to post multiple contents in my code in django rest framework?

这是我的 serializers.py:

from rest_framework import serializers
from .models import product
 


class productSerializer(serializers.ModelSerializer):
    class Meta:
        model= product
        fields="__all__"
 

views.py:

from django.shortcuts import render
from .models import *
from rest_framework import viewsets
from .serializers import productSerializer
from rest_framework.parsers import JSONParser

class productviewset(viewsets.ModelViewSet):
    queryset=product.objects.all()
    serializer_class=productSerializer 
    

当我想要post多个这样的内容时:

[
  {
     "Number": 1,
     "name": "1005001697316642",
     "image": "https://",
     "description": "fffffffff",
     "price": "USD 23.43",
     "buy": "https://"
  },
  {
     "Number": 2,
     "name": "1005002480978025",
     "image": "https://",
     "description": "dffdfdddddddddddddd",
     "price": "USD 0.89",
     "buy": "https://"
   }
 ]

我收到这个错误:

HTTP 400 Bad Request

Allow: GET, POST, HEAD, OPTIONS

Content-Type: application/json

Vary: Accept

{ "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] }

我应该怎么做才能post多个内容?

您必须覆盖 create 方法以允许多个对象, 所以我们将在继承ModelViewSet的class范围内进行覆盖, 如下图:

def create(self, request):
serialized = MovieTicketSerializer(data=request.data, many=True)
if serialized.is_valid():
    serialized.save()
    return Response(serialized.data, status=status.HTTP_201_CREATED)
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)