python - 在 Django Rest Framework (2.3.5) 中序列化 ManyToMany 抛出 ValueError

标签 python django rest serialization django-rest-framework

我假设我有一个非常简单的序列化程序设置,但是当我尝试将数据放入我的 API 时,出现以下错误:

ValueError: instance should be a queryset or other iterable with many=True

这是 View :

class QuizAPI(generics.RetrieveUpdateDestroyAPIView):
    model = Quiz
    serializer_class = QuizSerializer
    lookup_field = 'activity_id'

和序列化器:

class MediaResourceSerializer(serializers.ModelSerializer):
    owner = serializers.PrimaryKeyRelatedField(many=False, read_only=True)

    class Meta:
        model = MediaResource
        fields = ('owner', 'name', 'type', 'url')

class AnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Answer
        fields = ('text','is_correct','order')

class QuestionSerializer(serializers.ModelSerializer):
    answers = AnswerSerializer(many=True, required=False)
    resources = MediaResourceSerializer(many=True, required=False)

    class Meta:
        model = Question
        fields = ( 
            'question_id', 
            'type', 
            'order', 
            'question_text', 
            'explanation', 
            'resources', 
            'grading_weight', 
            'answers' 
        )

class QuizSerializer(serializers.ModelSerializer):
    questions = QuestionSerializer(many=True, required=False)
    created_by = serializers.PrimaryKeyRelatedField(many=False, read_only=True)

    class Meta:
        model = Quiz
        fields = (
            'activity_id', 
            'name',  
            'is_hidden', 
            'created_by', 
            'created_date', 
            'last_updated', 
            'sharable', 
            'questions'
        )

如果我从 QuizSerializer 中注释掉“问题”字段,它运行得很好(当然没有问题数据)。

** 编辑: 这是 PUT 调用有效负载:

activity_id: 4
created_by: 1
created_date: "2013-07-29T20:39:47.981Z"
is_hidden: false
last_updated: null
name: "This is only a test"
questions: []
sharable: true

最佳答案

问题看起来是嵌套表示 do not support read–write ,并且为写入操作序列化平面结构是可行的方法。

关于python - 在 Django Rest Framework (2.3.5) 中序列化 ManyToMany 抛出 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17935638/

相关文章:

python - 可以在 Google App Engine 上使用 Python Requests 库吗?

python - 将tensorflow object detection api与opencv的centroid tracking算法集成

python - 使用权限下载文件

python - 如何通过 Python urllib 将 JSON 数据发送到 Django 应用程序?

mysql - 安全多公司协会

python - 处理大量 list

python - BytesIO 对象到图像

javascript - 为什么我的表单在 ng-repeat 内部时不起作用?

django: SECURE_PROXY_SSL_HEADER 需要 referer

ios - 我应该如何创建和传递用户 token ?