标签:mod return div sel load generics ret max framework
导入
from rest_framework.parsers import JSONParser, FormParser, MultiPartParser, FileUploadParser
默认设置
‘DEFAULT_PARSER_CLASSES‘: ( ‘rest_framework.parsers.JSONParser‘, # application/json ‘rest_framework.parsers.FormParser‘, # application/x-www-form-urlencoded ‘rest_framework.parsers.MultiPartParser‘ # multipart/form-data ),
补充 FileUploadParser # */*
from rest_framework.parsers import JSONParser,FormParser class PublishViewSet(generics.ListCreateAPIView): parser_classes = [FormParser,JSONParser] queryset = Publish.objects.all() serializer_class = PublshSerializers def post(self, request, *args, **kwargs): print("request.data",request.data) return self.create(request, *args, **kwargs)
REST_FRAMEWORK={ "DEFAULT_PARSER_CLASSES":[‘rest_framework.parsers.FormParser‘,] }
导入
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination
class MyPageNumberPagination(PageNumberPagination): """自定义分页的类""" page_size = 1 # 每页多少条数据 page_query_param = ‘page‘ # 已什么url名分页 page_size_query_param = ‘size‘ # 临时更改每页多少页 max_page_size = 3 # 每页最多可显示多少条数据
方式一:针对自己写的逻辑
class BookView(APIView): def get(self, request): book_list = Book.objects.all() # bs = BookSerializers(book_list, many=True) # 自己写的serializer版本 # 分页 # pnp = MyPageNumberPagination() # 偏移页测试 pnp = MyLimitOffsetPagination() books_page = pnp.paginate_queryset(book_list, request, self) bs = BookModelSerializer(books_page, many=True, context={‘request‘: request}) # ModelSerializer组件的版本 # print(bs.data, "type-->", type(bs)) return Response(bs.data)
方式二:针对ModelViewSet
class AuthorViewSet(viewsets.ModelViewSet): # 分页 pagination_class = MyPageNumberPagination throttle_classes = [VisitRateThrottle, ] queryset = Author.objects.all() serializer_class = AuthorModelSerializer
class MyLimitOffsetPagination(LimitOffsetPagination): """自定义的偏移页的类""" default_limit = 2 # 每页显示多少条数据 limit_query_param = ‘limit‘ # 限制显示多少条数据 offset_query_param = ‘offset‘ # 偏移
方式一:针对自己写的逻辑
class BookView(APIView): def get(self, request): book_list = Book.objects.all() # bs = BookSerializers(book_list, many=True) # 自己写的serializer版本 # 分页 # pnp = MyPageNumberPagination() # 偏移页测试 pnp = MyLimitOffsetPagination() books_page = pnp.paginate_queryset(book_list, request, self) bs = BookModelSerializer(books_page, many=True, context={‘request‘: request}) # ModelSerializer组件的版本 # print(bs.data, "type-->", type(bs)) return Response(bs.data)
方式二:针对ModelViewSet
class AuthorViewSet(viewsets.ModelViewSet): # 偏移分页 pagination_class = MyLimitOffsetPagination throttle_classes = [VisitRateThrottle, ] queryset = Author.objects.all() serializer_class = AuthorModelSerializer
标签:mod return div sel load generics ret max framework
原文地址:https://www.cnblogs.com/sunch/p/9996745.html