如何序列化对象列表?

时间:2019-11-25 22:25:23

标签: python django django-rest-framework

Django-Rest-Framework文档(https://www.django-rest-framework.org/api-guide/serializers/)提供了以下示例,用于序列化对象列表:

queryset = Book.objects.all()
serializer = BookSerializer(queryset, many=True)
serializer.data

我尝试使用以下代码执行类似的操作:

@api_view(['GET'])
def postComments(request, pk):
    """
    Retrieve all comments with originalPostId = pk.
    """
    if request.method == 'GET':
        comments = Comment.objects.all()
        comments = comments.filter(originalPostId = pk)
        serializer = CommentSerializer(comments, many=True)
        if serializer.is_valid():
            return Response(serializer.data)
        logger.error(serializer.errors)

但是,立即发现以下错误:AssertionError: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance.

另一篇文章(django-rest-framework: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance)似乎解决了这个问题,但答案表明,在调用我的data=时放入CommentSerializer可以反序列化而不是序列化,这不是我想要。

但是,当我运行serializer = CommentSerializer(data=comments, many=True)行时,我得到了错误{'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "QuerySet".', code='not_a_list')]}

这是我的序列化器,以防万一:

    poster = UserSerializer()
    community = CommunitySerializer()
    originalPost = PostSerializer()
    class Meta:
        model = Comment
        fields = ['post', 'community', 'poster', 'originalPost', 'originalPostId']

    def create(self, validated_data):
        userData = validated_data.pop('poster')
        user = User.objects.get_or_create(username=userData['username'],
                                                       email=userData['email'],
                                                       first_name=userData['first_name'],
                                                       last_name=userData['last_name'],
                                                       password=userData['password'])[0]
        validated_data['poster'] = user
        communityData = validated_data.pop('community')
        community = Community.objects.get_or_create(name=communityData['name'])[0]
        validated_data['community'] = community

        originalPostData = validated_data.pop('originalPost')
        originalPost = Post.objects.get_or_create(id = validated_data['originalPostId'])[0]
        validated_data['originalPost'] = originalPost

        comment = Comment.objects.create(**validated_data)
        return comment```

2 个答案:

答案 0 :(得分:0)

@api_view(['GET'])
def postComments(request, pk):
    """
    Retrieve all comments with originalPostId = pk.
    """
    if request.method == 'GET':
        comments = Comment.objects.all()
        comments = comments.filter(originalPostId = pk)
        serializer = CommentSerializer(comments, many=True)
        return Response(serializer.data)

摆脱is_valid()支票可以正常使用。我想我只需要相信自己〜

答案 1 :(得分:0)

is_valid用于验证用户输入数据,因此不需要调用is_valid。

@api_view(['GET'])
def postComments(request, pk):
    """
    Retrieve all comments with originalPostId = pk.
    """
    if request.method == 'GET':
        comments = Comment.objects.filter(originalPostId = pk).all()
        serializer = CommentSerializer(comments, many=True)
        return Response(serializer.data)