django rest framework 自定义过滤器

默认的django rest framework是没有过滤器的,他的查找是基于id去查找,但是通常大多数的需求是我们需要进行过滤比如htttp:///www.igolang.cn/api/v1/hosts?name=liran&ip=1.1.1.1这就是进行所有数据的过滤,下面跟大家分享相关的django 插件

1、安装相关过滤模块

pip install django-filter

2、settings.py中加入app

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_filters'
]

3、定义views填写过滤字段

from rest_framework import filters
from django_filters import rest_framework

class CustomViewBase(viewsets.ModelViewSet):
    queryset = ''
    serializer_class = ''
    permission_classes = ()
    filter_fields = () #过滤字段
    search_fields = () #查找字段
    filter_backends = (rest_framework.DjangoFilterBackend, filters.SearchFilter,filters.OrderingFilter,) #格式固定

#这个时候当我们在进行上面的操作就会进行数据过滤

GET /api/v1/hosts/?ip=12.12.12.34

{
    "code": 200,
    "msg": "success",
    "count": 1,
    "next": null,
    "previous": null,
    "data": [
        {
            "id": 1,
            "hostname": "sj-jn-27-221.103.130",
            "type": 0,
            "vendor": "19",
            "ip": "12.12.12.34",
            "status": 0,
            "create_time": "2018-11-16T16:45:30.665053+08:00",
            "update_time": "2018-11-16T16:45:30.665087+08:00"
        }
    ]
}

你可能感兴趣的:(Python,Django)