django rest 3.1.1 - 具有 "many" 属性的一对多序列化器

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

我想创建一个简单的序列化程序,每个想要的人都可以添加一个有多个答案的问题(他想要多少)

一题多答

我的模特:

    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)

我的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

现在,当我 运行 网络时,我收到消息:

"Lists are not currently supported in HTML input."

请帮忙:)

第一次编辑

即使我删除了 ('many=True'),我在尝试 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.

那就是第二个问题:我不知道如何编辑的 create() 方法

您的引述回答了您的问题。内置 HTML 视图输入表单不支持列表。

似乎支持 planned for 3.1 but I don't see any mention in the 3.1 release notes

当您删除 ('many=True') 时,尝试 post 时出错,因为您尚未重写函数 create,您应该重写函数 create