How to create a function to pass a JSON in the Django Rest framework?

Asked

Viewed 347 times

0

I am studying drf and would like to create a function that would receive a list in JSON format and do an update by serializer.

To illustrate better follows as I am thinking.

example_serializer.py

class GarageViewSet(viewsets.ModelViewSet):
    queryset = Garage.objects.all()
    serializer_class = GarageSerializer
    model = Garage

class CarViewSet(viewsets.ModelViewSet):
    queryset = Car.objects.all()
    serializer_class = CarSerializer
    model = Car

I’m thinking something, sort of, like:

example

class GarageViewSet(viewsets.ModelViewSet):
    queryset = Garage.objects.all()
    serializer_class = GarageSerializer
    model = Garage

        @action(methods=['put'], detail=False)
        def update_car(self, request, *args, **kwargs):     
        if request.method == 'PUT':
            data = JSONParser().parse(request)
            serializer = CarSerializer(data=data, many=True)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse(serializer.data)
            return JsonResponse(serializer.errors, status=400)

When I try to pass, through the API, the data to be actualziados I get the following error:

{
    "non_field_errors": [
        "Necessário uma lista de itens, mas recebeu tipo \"dict\"."
    ]
}

Any north that can help me?

  • Do you have 2 serializers? and only one view? , what is your specific doubt? Have you tried to implode what you are thinking? what was the result? error?

  • ae @Sidon. Blz? Thanks for the response. The number of serializers and views was just to illustrate what I want. In addition, I put more data, including, a new attempt and error. Hugs

  • Okay, but where are the serializer designs/definitions?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.