在Django Rest框架中序列化许多tomany会抛出ValueError

[英]Serializing ManyToMany in Django Rest Framework (2.3.5) throws ValueError


I have what I assumed to be a pretty simple serializer setup, but when I attempt to PUT data to my API, I get the following error:

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

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

ValueError:实例应该是一个queryset或其他具有many=True的可迭代

Here's the view:

视图:

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

and the serializers:

序列化器:

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'
        )

If I comment out the 'questions' field from QuizSerializer it runs just fine (of course without question data).

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

** Edit: Here's the PUT call payload:

**编辑:这是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

1 个解决方案

#1


1  

The problem looks to be that nested representations do not support read–write, and serializing flat structures for write operations is the way to go.

问题似乎是嵌套表示不支持读写,而对写操作的平面结构进行序列化是解决方法。

智能推荐

如果文章对您有帮助,请打个赏吧
微信支付
支付宝支付

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/07/29/d1fbc21b40e759386d2ea3b6bfc764bf.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告