ModelSerializer中的Django自定义查询集

时间:2017-08-25 03:42:27

标签: django django-serializer

我的PostSerializer comments字段使用CommentSerializer。我想更改此CommentSerializer的查询集,以便它不会立即显示所有评论。这是代码

class PostSerializer(serializers.ModelSerializer):
    comments = SimplifiedCommentSerializer(
        many=True,
        required=False,
    )

    class Meta:
        model = Post
        fields = ('comments')

class SimplifiedCommentSerializer(serializers.ModelSerializer):
    content = serializers.TextField()

    # this function doesn't seem to work
    def get_queryset(self):
        return Comment.objects.all()[:10]

    class Meta:
        model = Comment
        fields = ('content')

我尝试在SimplifiedCommentSerializer中使用get_queryset,但我仍然得到所有评论而不是前10条。

1 个答案:

答案 0 :(得分:2)

尝试改变这一点:

def get_queryset(self):
    return Comment.objects.all()[:10]

成:

queryset = Comment.objects.all()[:10]

编辑:

创建一个视图集并外包上面的行:

class CommentViewSet(viewsets.ModelViewSet):
    queryset = Comment.objects.all()[:10]
    serializer_class = SimplifiedCommentSerializer

请看这个问题和答案: django REST framework - limited queryset for nested ModelSerializer?