如何在django-rest-framework中为我的自定义分页类使用pagination_class

时间:2015-04-21 10:42:24

标签: pagination django-rest-framework

我的分页类

class ArticleListPagination(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'page_size'

我的文章视图类

class Article(generics.GenericAPIView):

    queryset = Articles.objects.all()
    serializer_class = ArticlesSerializer
    pagination_class = ArticleListPagination

def get(self, request):
    queryset = self.get_queryset()
    serializer = ArticlesSerializer(queryset, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

我可以使用此

来使用自定义分页类
def get(self, request):
    queryset = self.get_queryset()
    page = ArticleListPagination()
    new = page.paginate_queryset(queryset, request)
    serializer = ArticlesSerializer(new, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

这是使用ArticleListPagination的正确方法吗?如果我在课堂上声明我的分页类是ArticleListPagination,为什么它不会更改返回的查询集对象。

3 个答案:

答案 0 :(得分:9)

表示django_rest_framework 3.0.x (或以下):

您可以直接扩展rest_framework.mixins.ListModelMixin,或者使用与此类似的getlist方法。

当然还需要generics.GenericAPIView

def list(self, request, *args, **kwargs):
    queryset = self.filter_queryset(self.get_queryset())
    page = self.paginate_queryset(queryset)
    if page is not None:
        # get_paginaion_serializer will read your DEFAULT_PAGINATION_SERIALIZER_CLASS 
        # or view.pagination_serializer_class 
        # we will talk the two variable later
        serializer = self.get_pagination_serializer(page)
    else:
        serializer = self.get_serializer(queryset, many=True)
    return Response(serializer.data)

如果您想将其配置为“全球”,则可以在settings.py

中进行配置
REST_FRAMEWORK = {
    # ...
    'DEFAULT_PAGINATION_SERIALIZER_CLASS': 'YourCustomPaginationSerializer',
    # ...
}

如果您只想设置特定视图:

属性为pagination_serializer_class,而不是pagination_class

class MyView(generics.GenericAPIView):
    pagination_serializer_class = YourCustomPaginationSerializerClass

表示django_rest_framework 3.1.x

略有不同,您可以先查看文档。 3.1 AnnouncementPagination Docs

您可以直接扩展rest_framework.mixins.ListModelMixin,或者使用与此类似的get方法。

当然还需要generics.GenericAPIView

def list(self, request, *args, **kwargs):
    queryset = self.filter_queryset(self.get_queryset())

    page = self.paginate_queryset(queryset)
    if page is not None:
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)

    serializer = self.get_serializer(queryset, many=True)
    return Response(serializer.data)

如果您想将其配置为“全球”,则可以在settings.py

中进行配置
REST_FRAMEWORK = {
    # ...
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'

    # ...
}

如果您只想设置特定视图:

class MyView(generics.GenericAPIView):
    pagination_class = YourCustomPaginationClass

答案 1 :(得分:6)

您可以在视图集中使用自定义分页并在自定义视图中更改

pagination.py

class OneByOneItems(pagination.PageNumberPagination):
    page_size = 2

    def get_paginated_response(self, data):
        return Response(OrderedDict([
             ('lastPage', self.page.paginator.count),
             ('countItemsOnPage', self.page_size),
             ('current', self.page.number),
             ('next', self.get_next_link()),
             ('previous', self.get_previous_link()),
             ('results', data)
         ]))

views.py

class LectionViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = LectionCourse.objects.all().order_by('-created_at')
    serializer_class = LectionSerializer

    @list_route(methods=['get'], url_path='get-lections/(?P<pk>[^/]+)')
    def get_lection(self, request, pk):
        self.pagination_class = OneByOneItems
        queryset = self.filter_queryset(self.queryset.filter(course=pk))
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)   

serializers.py

class CourseSerializer(serializers.ModelSerializer):
    author = UserCreatorSerializer(many=True)
    project = ProjectSerializer(many=True)

    class Meta:
        model = Course
        fields = ('id', 'theme', 'author', 'project')


class LectionSerializer(serializers.HyperlinkedModelSerializer):
    choose_course = CourseSerializer(source='course')

    class Meta:
        model = LectionCourse
        fields = ('id', 'title', 'video', 'preview_description', 'number', 'choose_course')

答案 2 :(得分:3)

我更喜欢使用自定义分页,因为它可以根据您的要求修改您的回复。这种方法不需要太多努力。

以下是我的代码......希望这会有所帮助。

custom_pagination.py

from rest_framework import status
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response

class CustomPagination(LimitOffsetPagination):
def get_paginated_response(self, data):
    return Response({
        "status": True,
        "code": status.HTTP_200_OK,
        'next': self.get_next_link(),
        'previous': self.get_previous_link(),
        'count': self.count,
        'results': data
    })

在您的视图中,您需要做的就是调用两个函数,即i-e paginate_queryset和您在分页类get_paginated_response中创建的函数。 “pagination_queryset”将queryset作为参数,并将该结果传递给序列化程序,最后调用“get_paginated_response”,它将序列化数据作为参数和结果返回响应。

page = self.paginate_queryset(query_set)
serializer_class = <Your Serializer>(page, many=True,)
return self.get_paginated_response(serializer_search_user.data)

最后在“settings.py”中声明自定义序列化类。

REST_FRAMEWORK = {
      'DEFAULT_PAGINATION_CLASS':'<your_app>.<your_peckage>.custom_pagination.CustomPagination',
      'PAGE_SIZE': 5
}