Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest 3.1.1 - one to many serializer with "many" attribute

I want to create a simple serializer that everyone who want will be able to add a Question with multi Answers (how many that he want)

one Question- multi Answers

  • I want to be able to add with the build in html form and not to edit the json.

my models:

    class Question(models.Model):
         question_text = models.CharField(max_length=30)

    class Answer(models.Model):
         question = models.ForeignKey(Question)
         answer_text = models.CharField(max_length=40)

my url.py

class AnswerSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Answer
        fields = ('answer_text',)


class QuestionSerializer(serializers.HyperlinkedModelSerializer):

    answers = AnswerSerializer(many=True)
    class Meta:
        model = Question
        fields = ('question_text', 'answers',)

class QuestionViewSet(viewsets.ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer

now, when i run the web I get the message:

"Lists are not currently supported in HTML input."

please help :)

first edit

even when i remove the ('many=True') i get an error while trying to post:

AssertionError at /questions/ The .create() method does not support writable nestedfields by default. Write an explicit .create() method for serializer api_project2.urls.QuestionSerializer, or set read_only=True on nested serializer fields.

thats creates m second problem: the create() method that i dont knwo how to edit

like image 968
Oz Bar-Shalom Avatar asked Sep 29 '22 02:09

Oz Bar-Shalom


2 Answers

when you remove the ('many=True'), you get an error while trying to post because you have not rewrite the function create, you should rewrite the function create

like image 64
Miguel Angel Bernal Colonia Avatar answered Oct 03 '22 00:10

Miguel Angel Bernal Colonia


Your quote answers your question. The built-in HTML view input forms do not support lists.

It seems that support was planned for 3.1 but I don't see any mention in the 3.1 release notes.

like image 43
Dwight Gunning Avatar answered Oct 03 '22 00:10

Dwight Gunning