详解drf中的ModelViewSet

开发十年,就只剩下这套Java开发体系了 >>>   hot3.png

详解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).当然也可以根据自己需要重新各种方法

类名 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/
223916_bL9y_2663968.jpg

你可能感兴趣的:(详解drf中的ModelViewSet)