Bootstrap

ModelViewSet实现过滤和增删改查

局部配置过滤

from django.shortcuts import render
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import ModelViewSet

from apps.app01.models import *
from apps.app01.sers import *

class MyPage(PageNumberPagination):
    page_size_query_param = 'max_page'
    page_query_param = 'page'

class GoodsListViewSet(viewsets.ModelViewSet):
    """
    list:
        商品列表
    read:
        商品详情
    create:
        增加商品
    update:
        更改商品
    partial_update:
        部分更改
    delete:
        删除商品
    """
    # 必须定义一个默认排序否则会报错
    queryset = Goods.objects.all().order_by('id')
    # 分页
    pagination_class = MyPage
    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')

全局配置ModelViewSet过滤及分页

REST_FRAMEWORK = {
    # 限次
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    },
    # 过滤器
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
        'rest_framework.filters.OrderingFilter'),
    # 分页
    # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    # 'PAGE_SIZE': 3  # 每页数目
}

View单独增上改查,没有分页

view界面

#课程类别
class CourseTypeView(ModelViewSet):
    queryset = CourseType.objects.all()         //获取所有数据
    serializer_class = CourseTagSer     //序列化器,完成增删改查

url路由页面

routers = DefaultRouter()         默认使用defaul路由
routers.register("type",CourseTypeView)      注册这个模型类
urlpatterns = [

    path('', include(routers.urls)),         #子路由配置
]

ModelViewSet使用action使用规范

view界面

class BookInfoModelViewSet(ModelViewSet):
    queryset = Books.objects.all()
    serializer_class =BooksSer
    # 搜索
    search_fields=('=title','=desc')
    # 排序
    ordering_fields = ('read', 'pub_date')


    @action(methods=['get'],detail=False)    #用get方法,不带pk时候用False
    def is_del(self,request):
        #获取删除的图书列表
        queryset=self.queryset.filter(is_delete=True)
        ser=self.serializer_class(queryset,many=True)
        return JsonResponse(ser.data,safe=False)

    @action(methods=['get'], detail=True)   #如果为True必须携带pk
    def only_title(self,request,pk):
        #如果带pk,self,中提供了根据pk获取的那个对象
        instance=self.get_object()   #根据pk,获取到的数据
        data_dict = {
            'title': instance.title,
            'pub_date': instance.pub_date,
            'desc': instance.desc,
            'read': instance.read,
            'is_delete': instance.is_delete
        }
        return JsonResponse(data_dict)

    @action(methods=['get'], detail=False)  # 用get方法,不带pk时候用False
    def is_del(self, request):
        # 获取删除的图书列表
        queryset = self.queryset.update(is_delete=True)          #调用上面的获取所有数据,然后吧数据全部修改为删除状态
        ser = self.serializer_class(queryset, many=True)            #序列化展示
        return JsonResponse({'msg':'操作成功'})

url路由页面

from django.urls import path
from rest_framework.routers import DefaultRouter,SimpleRouter       #SimpleRouter为简单的路由展示

from demoapp.views import BooksListView, BooksInfoView, BookInfoModelViewSet


router=DefaultRouter()                    #调用DefaultRouter
router.register('books',BookInfoModelViewSet)        #导入url后面会自动生成/,调用view




urlpatterns=[
    # path('books/',BooksListView.as_view()),    #添加数据
    # path('books/<int:pk>/',BooksListView.as_view()),    #查询单个数据
    # path('books/is_del/',BooksInfoView.as_view()),
    # path('booksinfo/is_del/',BookInfoModelViewSet.as_view({'get': 'is_del'})),
    # path('booksinfo/<int:pk>/only_title/',BookInfoModelViewSet.as_view({'get': 'only_title'}))


]

urlpatterns+=router.urls          #拼接modelviewset里的路由
print(router.urls)
;