django 如何序列化对象列表?

oxcyiej7  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(139)

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 nodata=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)似乎解决了这个问题,但答案表明,在调用我的CommentSerializer时放入data=将有助于并行化而不是串行化,这不是我想要的。
但是,当我运行serializer = CommentSerializer(data=comments, many=True)行时,我得到错误{'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "QuerySet".', code='not_a_list')]}
这是我的序列化器,以防万一:

class CommentSerializer(serializers.ModelSerializer):
    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
2uluyalo

2uluyalo1#

@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()检查使它工作。~我想我只是需要相信自己~

qojgxg4l

qojgxg4l2#

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)

相关问题