-1

i trying send a list in a POST requisition in Django Rest Framework. My objective like this: Nested Relationship, but i want a list.

What i need:

{
     "id": 3435,
     "titulo": "Livro x",
     "editora": "Editora x",
     "foto": "https://i.imgur.com/imagem.jpg",
     "autores": ["Autor 1"]
}

What i am getting:

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

My serializers.py file:

from rest_framework.serializers import ModelSerializer

from .models import Autor, Livro

class AutorSerializer(ModelSerializer):

    class Meta:
        model = Autor
        fields = ('nome')


class LivroSerializer(ModelSerializer):

    autores = AutorSerializer(many=True)

    class Meta:
        model = Livro
        fields = ('id', 'titulo', 'editora', 'autores')

    def create_autores(self, autores, livro):
        for autor in autores:
            obj = Autor.objects.create(**autor)
            livro.autores.add(obj)

    def create(self, validated_data, **kwargs):
        autores = validated_data.pop('autores')

        livro = Livro.objects.create(**validated_data)
        self.create_autores(autores, livro)

        return livro

Where i going wrong?

  • Does this answer your question? [How to access forgin key value in react from django api](https://stackoverflow.com/questions/67523331/how-to-access-forgin-key-value-in-react-from-django-api) – Ankit Tiwari Oct 12 '21 at 13:57
  • I tried. Dont work. I have a many to many relationship. But, thanks. – hidantachi Oct 12 '21 at 14:16
  • What happens if you change this `autores = AutorSerializer(many=True)` to this `autores = AutorSerializer(many=True, read_only=True)`? – Daniel Oct 12 '21 at 16:00
  • @Daniel, with `autores = AutorSerializer(many=True, read_only=True)`, i receive `Key error 'autores'` – hidantachi Oct 12 '21 at 17:26

1 Answers1

0

in your views.py, for the respective view add the below code for create, if required on update.

class AutorViewset(viewsets.ModelViewSet):
    queryset=Autor.objects.all()
    serializer_class=AutorSerializer

    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)

This will allow you to pass list as input to Autor model

LiquidDeath
  • 1,768
  • 1
  • 7
  • 18