继承ModelViewSet-增删改查分页过滤

**
ViewSetMixin累源码分析
我们主要是来看下为什么通过url配置和ModelViewSet几行代码,就能实现request的restful协议请求
ModelViewSet类继承关系比较复杂,我先抛出一张简陋的父子关系继承图
**
继承ModelViewSet-增删改查分页过滤_第1张图片
ModelViewSet继承MiXin 我们实现api接口数据请求时,可以利用mixins模块来实现,也就是ModelViewSet的4个继承父类,分别实现了增加、获取单条数据、更新数据、删除销毁数据、获取所有表数据的功能,之前的mixins源码简单分析过,这里就不在一一重复赘述,后续的分析中,会拿出一个来配合GenericViewSet类代码进行分析

ModelViewSet 源码

class ModelViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):
    """
    A viewset that provides default `create()`, `retrieve()`, `update()`,
    `partial_update()`, `destroy()` and `list()` actions.
    """
    pass

Serializers.py

from rest_framework import serializers
from demoapp import models as dm1model

class UserSer(serializers.ModelSerializer):
    class Meta:
        #指定模型类
        model = dm1model.User   
        #指定序列化字段
        fields = "__all__"   #所有字段
        #fields = ("username","home")   #其中某几个字段
        #序列化深度,是否序列化外键
        depth = 1
        #只序列化字段
				read_only_fields = ('id', 'bread', 'bcomment')
        #额外参数,修改字段设置
        #extra_kwargs = {
     
        #   'age': {'min_value': 0, 'required': True},
        #   'hight': {'min_value': 0, 'required': True},
        #}

url.py

from django.urls import path,include,re_path
from demo3app.views import *
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register("user",UserModelView)



urlpatterns = [
    path("",include(router.urls)),
    # path("index1/",Index1.as_view()),

]

Views.py

from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from demoapp import models as dm1model
from demo3app import serializers as dm3ser
# Create your views here.

class UserModelView(ModelViewSet):
    queryset = dm1model.User.objects.all()
    serializer_class = dm3ser.UserSer

ModelViewSet的过滤,排序和分页

- 下载所需三方包

`pip install django-filter`

########settings.py#########

INSTALLED_APPS = [
    ...
    'django_filters',  # 需要注册应用,
]

#全局配置过滤器
REST_FRAMEWORK = {
     
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}


#########demp3app/views.py##############


from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from demoapp import models as dm1model
from demo3app import serializers as dm3ser
from django_filters.rest_framework import DjangoFilterBackend

# Create your views here.

#使用全局过滤器
class UserModelView(ModelViewSet):
    queryset = dm1model.User.objects.all()
    serializer_class = dm3ser.UserSer
    filter_fields = ("username","age","home")

    
#局部使用过滤器
class UserModelView(ModelViewSet):
    queryset = dm1model.User.objects.all()
    serializer_class = dm3ser.UserSer
    filter_backends = [DjangoFilterBackend]  #申明配置过滤器
    filter_fields = ("username","age","home")

- 请求时在get请求里最后加上对应的条件

`http://127.0.0.1:8000/dm3/user/?home=河南&username=peter2`

排序

########settings.py#########


#全局配置过滤器
REST_FRAMEWORK = {
     
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.OrderingFilter',)
}

#########demp3app/views.py##############


from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from demoapp import models as dm1model
from demo3app import serializers as dm3ser
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
# Create your views here.

#全局配置使用
class UserModelView(ModelViewSet):
    queryset = dm1model.User.objects.all()
    serializer_class = dm3ser.UserSer
    ordering_fields = ("age","hight")


#局部配置使用    
class UserModelView(ModelViewSet):
    queryset = dm1model.User.objects.all()
    serializer_class = dm3ser.UserSer
    filter_backends = [OrderingFilter]   #申明配置排序过滤器
    ordering_fields = ("age","hight")

- 请求时在get请求里最后加上对应的条件

`http://127.0.0.1:8000/dm3/user/?ordering=hight`

过滤和排序联合使用

########settings.py#########


REST_FRAMEWORK = {
     
    #过滤器
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',
                                'rest_framework.filters.OrderingFilter')
}

#########demp3app/views.py##############



from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from demoapp import models as dm1model
from demo3app import serializers as dm3ser
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
# Create your views here.

class UserModelView(ModelViewSet):
    queryset = dm1model.User.objects.all()
    serializer_class = dm3ser.UserSer
    #filter_backends = [OrderingFilter,DjangoFilterBackend]  #如过未设置全局配置,需要在这局部配置
    ordering_fields = ("age","hight")
    filter_fields = ("username","age","home")


- 请求时在get请求里最后加上对应的条件

`http://127.0.0.1:8000/dm3/user/?ordering=hight&home="河南"`

分页

########settings.py#########


REST_FRAMEWORK = {
     
    
    'DEFAULT_PAGINATION_CLASS':  'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 3  # 每页数目

}
- 请求时在get请求里最后加上对应的条件

`http://127.0.0.1:8000/dm3/user/?page=3`

**局部配置和使用**
#########demp3app/views.py##############



from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from demoapp import models as dm1model
from demo3app import serializers as dm3ser
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.pagination import PageNumberPagination
# Create your views here.

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


class UserModelView(ModelViewSet):
    queryset = dm1model.User.objects.all()
    serializer_class = dm3ser.UserSer
    pagination_class = MyPage

- 请求时在get请求里最后加上对应的条件

`http://127.0.0.1:8000/dm3/user/?page=3&max_page=3`


ModelViewSet分开指定序列化器

from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from demoapp import models as dm1model
from demo3app import serializers as dm3ser
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.pagination import PageNumberPagination
# Create your views here.

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


class UserModelView(ModelViewSet):
    queryset = dm1model.User.objects.all()
    serializer_class = dm3ser.UserSer
    pagination_class = MyPage
    
     # 根据不同的请求, 获得不同的序列化器
    def get_serializer_class(self):
        if self.action == 'list':
            return UserSer
        else:
            return UserSimpleSer

你可能感兴趣的:(django)