我正在嘗試創建一個回傳帖子串列的端點。我想說每頁 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
uj5u.com熱心網友回復:
您必須將視圖串列函式撰寫為 -
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 類中使用的所有屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/422732.html
標籤:
上一篇:是否有可能在Django自定義身份驗證中對密碼設定條件?
下一篇:如何正確擴展樹枝三元陳述句?
