所以这是我的视图集:
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
permission_classes = (IsAuthenticated, IsLikeOrOwnerDeleteOrReadOnly,)
def perform_create(self, serializer):
serializer.save(owner=self.request.user, location=self.request.user.userextended.location)
@detail_route(methods=['post'], permission_classes=[IsFromLoactionOrReadOnly])
def like(self, request, pk=None):
post = self.get_object()
post.usersVoted.add(request.user)
return Response(status=status.HTTP_204_NO_CONTENT)
这是我的 URL / 路由器:
router.register(r'posts', views.PostViewSet)
现在,当我访问此 URL 时:
/posts
DRF 发送所有帖子和序列化程序(或者我认为.. 我还没有很多帖子,所以我假设它发送所有帖子)。我想要做的是能够将我的 ViewSet 序列化的帖子数量限制为 10。我想要序列化的 10 个对象取决于我想要强制 API 用户使用 URL 发送的页码。例如,我想强制用户发送一个带有 URL 的号码,如下所示:
/posts/x
在后端,我想用 pk x 将帖子序列化为 x+9(所以如果我们假设 x=1,那么我想用 pk=1、pk=2、pk=3 来序列化帖子... pk= 10.)。DRF可以做到这一点吗?我猜我使用Pagination
的是因为当我阅读文档时,它看起来像是我需要的,但我无法完全理解分页到底是什么以及如何使用它来完成我想要的。这是分页的文档:http: //www.django-rest-framework.org/api-guide/pagination/
提前致谢。