Home > OS >  Django REST Framework unable to send multiple data
Django REST Framework unable to send multiple data

Time:10-15

I am trying to send multiple JSON data in a single POST as a list like -

[
 {
    "name": "data",
 },
 {
    "name": "data",
 }
]

but getting the following error.

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

Here are my codes -

Serializers.py

class my_serializer_name(serializers.ModelSerializer):
class Meta:
    model = my_model
    fields = '__all__'

def validate(self, data):
    #Performing validation
    ......
    ......

viewsets.py

class my_viewset(viewsets.ModelViewSet):
queryset = models.my_model.objects.all()
serializer_class = serializers.my_serializer
http_method_names = ['get', 'post']

def list(self, request):
    # Note the use of `get_queryset()` instead of `self.queryset`
    queryset = self.get_queryset()
    serializer = serializers.my_serializer(queryset, many=True)
    return Response(serializer.data)

router.py

router = routers.DefaultRouter()
router.register('name' , my_viewset)

How to solve this issue?

CodePudding user response:

I added the Create method on the viewsets.py file and it seems to be working fine.

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data, many=isinstance(request.data,list))
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

CodePudding user response:

One way of doing it is to override post method to specify serializer : instead of default serializer, use many=True

class my_viewset(viewsets.ModelViewSet):
    queryset = models.my_model.objects.all()
    serializer_class = serializers.my_serializer
    http_method_names = ['get', 'post']

    def post(self, request):
        serialized = my_serializer_name(data=request.data, many=True)
        serialized.is_valid(raise_exception=True)
        serialized.save()
  • Related