我正在尝试创建一个返回帖子列表的端点。我想说每页 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