Oz Bar-Shalom
Oz Bar-Shalom

Reputation: 1855

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

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

Upvotes: 5

Views: 1773

Answers (2)

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

Upvotes: 3

Dwight Gunning
Dwight Gunning

Reputation: 2525

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.

Upvotes: 1

Related Questions