0

我正在尝试创建一个返回帖子列表的端点。我想说每页 2 个帖子(仅用于测试!我知道导致问题的数字并不大!)。这是我的 意见.py

class blogsViewSet(ModelViewSet):
    queryset = Posts.objects.all()
    serializer_class = PostSerializer
    pagination_class = pagination.CustomPagination

    
    def list(self, request):
        data = request.data
        uid = data['uid']
        context = {"user": uid}
        blogs = Posts.objects.all()
        serializer = PostSerializer(blogs, many= True, context= context)
        return Response(serializer.data)

这是我的 serializers.py

class PostSerializer(ModelSerializer):    
    isLiked = serializers.SerializerMethodField(method_name='check_react')
    totalLikes = serializers.SerializerMethodField(method_name='get_likes')
    totalComments = serializers.SerializerMethodField(method_name='get_comments')

    def check_react(self, post):
        userObj = Users.objects.get(userID = self.context['user'])
        #print(type(userObj))
        
        if Likes.objects.filter(postID = post, userID = userObj).exists():
            isLiked = Likes.objects.get(postID = post, userID = userObj)
            likeObj = LikeSerializer(isLiked)
            #print('isLiked: ', likeObj.data['isLiked'])
            return (likeObj.data['isLiked'])
        return(False)
        #print(isLiked)
    
    def get_likes(self, post):
        count = Likes.objects.filter(postID = post).count()
        return count

    def get_comments(self, post):
        count = PostsComments.objects.filter(postID = post).count()
        return count

    class Meta:
        model = Posts
        fields = '__all__'

而且,这是我的 pagination.py

from rest_framework import pagination

class CustomPagination(pagination.PageNumberPagination):
    page_size = 2
    page_size_query_param = 'page_size'
    max_page_size = 3
    page_query_param = 'p'

我在views.py上导入这个类,当我尝试通过userMVS检索用户列表时它按预期工作

class userMVS(ModelViewSet):
    queryset = Users.objects.all()
    serializer_class = UserSerializer
    pagination_class = pagination.CustomPagination
4

1 回答 1

0

您必须将视图列表函数编写为 -

def list(self, request, *args, **kwargs):
    queryset = Posts.objects.all()
    paginatedResult = self.paginate_queryset(queryset)
    serializer = self.get_serializer(paginatedResult, many=True)
    return Response(serializer.data)

编辑 -

假设这是我的分页类 -

class CustomPagination(PageNumberPagination):
    page_size = 8
    page_query_param = "pageNumber"

并在类级别以这种方式使用,并在上面的列表函数中提到 -

class blogsViewSet(ModelViewSet):
    queryset = Posts.objects.all()
    serializer_class = PostSerializer
    pagination_class = CustomPagination

那么这是应该工作的网址

http://localhost:8000/urlofpostviewset/?pageNumber=passThePageNumber

请从文档中阅读您在 CustomPagination 类中使用的所有属性。

于 2022-01-27T16:30:19.470 回答