转自:https://blog.csdn.net/weixin_36646275/article/details/83965621
详解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/
view的用法说明:
class GoodsListViewSet(viewsets.ModelViewSet):
"""
list:
商品列表
read:
商品详情
create:
增加商品
update:
更改商品
partial_update:
部分更改
delete:
删除商品
"""
# 必须定义一个默认排序否则会报错
queryset = Goods.objects.all().order_by('id')
# 分页
pagination_class = GoodsPagination
serializer_class = GoodsSerializer
# 过滤
filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
filter_class = GoodsFilters
# 搜索
search_fields = ('name', 'goods_brief', 'goods_desc')
# 排序
ordering_fields = ('sold_num', 'shop_price')