2015-12-02 69 views
0

這是我的看法巫工程確定:Django的REST的架構,如何分頁

from django.http import Http404, HttpResponse, HttpResponseRedirect 
from django.views.decorators.csrf import csrf_exempt 
from rest_framework.renderers import JSONRenderer 
from rest_framework.parsers import JSONParser 
from rest_framework import serializers 
from gamerauntsia.berriak.serializers import BerriaSerializer 
from rest_framework.response import Response 
import json 



class JSONResponse(HttpResponse): 
    """ 
    An HttpResponse that renders its content into JSON. 
    """ 
    def __init__(self, data, **kwargs): 
     content = JSONRenderer().render(data) 
     kwargs['content_type'] = 'application/json' 
     super(JSONResponse, self).__init__(content, **kwargs) 

@csrf_exempt 
def app_berria_list(request): 
    if request.method == 'GET': 
     berriak = Berria.objects.all() 
     serializer = BerriaSerializer(berriak, many=True) 
     return JSONResponse(serializer.data) 

我想通過5項分頁響應,所以我試圖在settings.py添加此:

REST_FRAMEWORK = { 
    'DEFAULT_AUTHENTICATION_CLASSES': [ 
     'rest_framework.authentication.SessionAuthentication', 
     'rest_framework.authentication.TokenAuthentication', 
    ], 
    'DEFAULT_PERMISSION_CLASSES': [ 
     'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' 
    ], 
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 
    'PAGE_SIZE': 5 
} 

我需要改變一些東西才能使它工作嗎? 在此先感謝

回答

1

串行器不分頁自己,你必須調用分類類與查詢集作爲參數。默認情況下,內置的rest_framework.viewsets.ModelViewSet可以執行JSON解析/呈現和分頁,而無需執行任何操作。

爲什麼不能有一個視圖集類如:

from rest_framework import viewsets 
class BerriaViewSet(viewsets.ModelViewSet): 
    queryset = Berria.objects.all() 
    serializer_class = BerriaSerializer 

這會做你想要我相信一切。

如果你堅持這樣做,你現在的樣子,但是,你可以做到以下幾點:

from rest_framework.pagination import PageNumberPagination 
@csrf_exempt 
def app_berria_list(request): 
    if request.method == 'GET': 
     berriak = Berria.objects.all() 
     paginator = PageNumberPagination() 
     page = paginator.paginate_queryset(berriak, request) 
     serializer = BerriaSerializer(page, many=True, context={'request': request}) 
     return paginator.get_paginated_response(serializer.data) 
+0

I'll與視圖集中去......那太棒了!我不知道他們:D –