简体   繁体   English

如何序列化对象列表?

[英]How to serialize a list of objects?

The Django-Rest-Framework documentation ( https://www.django-rest-framework.org/api-guide/serializers/ ) gives the following example for serializing a list of objects: Django-Rest-Framework 文档 ( https://www.django-rest-framework.org/api-guide/serializers/ ) 提供了以下用于序列化对象列表的示例:

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

I try to do something similar with the following code:我尝试使用以下代码执行类似操作:

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

However, right off the bat I get the following error: AssertionError: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance.但是,立即出现以下错误: AssertionError: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance.

This other post ( django-rest-framework: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance ) seems to address this, but the answer suggests that putting in data= when calling my CommentSerializer would serve to deserialize instead of serialize, which is not what I want.一篇文章( django-rest-framework:无法调用`.is_valid()`,因为在实例化序列化器实例时没有传递`data=`关键字参数)似乎解决了这个问题,但答案表明在调用时放入data=我的CommentSerializer将用于反序列化而不是序列化,这不是我想要的。

However, when I do run with the line serializer = CommentSerializer(data=comments, many=True) I get the error {'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "QuerySet".', code='not_a_list')]}但是,当我使用serializer = CommentSerializer(data=comments, many=True)行运行时serializer = CommentSerializer(data=comments, many=True)我收到错误{'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "QuerySet".', code='not_a_list')]}

Here is my serializer, in case that matters:这是我的序列化程序,以防万一:

    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```
@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)

Getting rid of the is_valid() check made it work.摆脱is_valid()检查使它起作用。 I guess I just needed to believe in myself~我想我只需要相信自己吧~

is_valid is used for the validating user input data, so no need of call is_valid. 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM