我的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条。
答案 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?