django-rest-framework view and url

django-rest-framework view

GenericView

class GenericView(GenericAPIView):
    queryset = models.Role.objects.all()
    serializer_class = serializers.RoleSerializer
    pagination_class = PageNumberPagination

    def get(self, request):
        # 获取数据
        data = self.get_queryset()
        # 获取分页数据
        page_data = self.paginate_queryset(data)
        # 获取序列化数据
        resp = self.get_serializer(instance=page_data, many=True)
        return Response(resp.data)
  • GenericView do a little in the original package ApiView, there are three main methods used
    • get_queryset : Get queryset object query
    • paginate_queryset: Gets the object after page, need to accept a parameter objects queryset
    • get_serializer: Serialized data, the development of serialized objects and the development of many parameters

GenericViewSet

class GenericView(GenericViewSet):

    def list(self, request):
        return Response('list')
from django.conf.urls import re_path

from . import views

urlpatterns = [
    re_path(r'^index/', views.GenericView.as_view({'get': 'list'})),
]
  • GenericViewSet GenericView use with substantially no difference, only a function of the corresponding request method requires custom
    • url as_view method requires passing a parameter dictionary, the dictionary is the key corresponding to the request method, value is corresponding to the request handler method

ModelViewSet

class GenericView(ModelViewSet):
    queryset = models.Role.objects.all()
    serializer_class = serializers.RoleSerializer
    pagination_class = PageNumberPagination
  • ModelViewSet more senior, additions and deletions to its default implementation of the method of investigation, only needs to configure the corresponding attribute on it

url

from django.conf.urls import re_path

from . import views

urlpatterns = [
    re_path(r'^index/', views.GenericView.as_view({'get': 'list', 'post': 'update'})),
]

Automatic route generation

from django.urls import path, include, re_path
from rest_framework import routers

from . import views

route = routers.DefaultRouter()

route.register('index', views.GenericView)

urlpatterns = [
    re_path('', include(route.urls))
]

Guess you like

Origin www.cnblogs.com/ivy-blogs/p/11665535.html