詳解drf中的ModelViewSet

詳解drf中的ModelViewSet

使用:

# view.py
from rest_framework import viewsets
class PersonalSet(viewsets.ModelViewSet):
    queryset = Personal.objects.all()
    serializer_class = PersonalSerializer
    pagination_class = LargeResultsSetPagination
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication,)
# urls.py
from django.urls import include, path
from rest_framework import routers
from rest_framework.authtoken import views
from rest_framework_jwt.views import obtain_jwt_token

from okr_rest.views import TestGroupSet, QuarterSet, PersonalSet

router = routers.DefaultRouter()
router.register("test_group", TestGroupSet)
router.register("quarter", QuarterSet, base_name="quarter")
router.register("personal", PersonalSet)

urlpatterns = [
    path("", include(router.urls)),
    path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
    path("api-token-auth/", views.obtain_auth_token),
    path("jwt-auth/", obtain_jwt_token)

說明:

ModelViewSet中默認已經有五個混入類直接封裝好處理各類請求.對應關係已經訪問url以下: DRF默認已經封裝了五種經常使用的方法,但因爲封裝不一樣須要在訪問的時候注意訪問url(detail是否爲true).固然也能夠根據本身須要從新各類方法python

類名 HTTP方法 說明 detail URL示例
mixins.CreateModelMixin POST 建立數據 False http://localhost/api/personal/
mixins.RetrieveModelMixin GET 檢索數據 True http://localhost/api/personal/30/
mixins.UpdateModelMixin PUT 更新數據 True http://localhost/api/personal/30/
mixins.DestroyModelMixin DELETE 刪除數據 True http://localhost/api/personal/30/
mixins.ListModelMixin GET 獲取數據 False http://localhost/api/personal/
相關文章
相關標籤/搜索