Loading

Django drf 过滤

Django drf 过滤

17.1 全局配置

安装模块

pip install django-filter

注册模块

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',  # django原生接口
    'app01',  # drf接口
    'sers',  # 序列化器的使用
    'req',  # drf提供的请求与响应
    'viewdemo',  # 视图
    'school',  # 序列化器的嵌套
    'opt',  # drf组件
    'django_filters', # 过滤
    'rest_framework',
]

配置过滤类

REST_FRAMEWORK = {
    
    ......
    
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
}

视图

class ExampleView4(ModelViewSet):
    queryset = studentsInfo.objects.all()
    serializer_class = studentSerializer
    filterset_fields = ["age", "sex", "classroom"] # 可以进行过滤的字段

路由

from . import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register("filter", views.ExampleView4, basename="filter")
urlpatterns = [
    
] + router.urls

访问效果

GET /opt/filter/?sex=女
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": 2,
        "name": "小红",
        "sex": "女",
        "age": 18,
        "classroom": "301",
        "info": "这个人很懒,什么也没有留下"
    },
    {
        "id": 15,
        "name": "彭于晏",
        "sex": "女",
        "age": 0,
        "classroom": "000",
        "info": "要做个猛男,要猛!"
    }
]

17.2 局部配置

视图

from django_filters.rest_framework import DjangoFilterBackend

class ExampleView4(ModelViewSet):
    queryset = studentsInfo.objects.all()
    serializer_class = studentSerializer
    filter_backends = [DjangoFilterBackend] # 过滤器类
    filterset_fields = ["age", "sex", "classroom"] # 可以进行过滤的字段

路由

from . import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register("filter", views.ExampleView4, basename="filter")
urlpatterns = [
    
] + router.urls

访问效果

GET /opt/filter/?classroom=310
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": 5,
        "name": "闵麒良",
        "sex": "男",
        "age": 23,
        "classroom": "310",
        "info": "河工胡歌"
    },
    {
        "id": 16,
        "name": "范玉才",
        "sex": "男",
        "age": 23,
        "classroom": "310",
        "info": "要做个猛男,要猛!"
    },
    {
        "id": 17,
        "name": "胡歌",
        "sex": "男",
        "age": 30,
        "classroom": "310",
        "info": "帅帅帅"
    }
]
posted @ 2022-10-24 17:32  minqiliang  阅读(119)  评论(0编辑  收藏  举报
-->