1. 过滤
在之前所写的五个接口中,只有获取所有需要过滤,其他接口都不需要。如在访问的时候带参数过滤出自己想要的数据。
http://127.0.0.1:8080/?search=活着
1.1 内置过滤类
views.py
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from 应用名.models import Book # 数据库
from 应用名.serializer import BookSerializer # 序列化器
from rest_framework.filters import SearchFilter
class BookView(GenericViewSet, ListModelMixin):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_backends = [SearchFilter,]
# 过滤name
# search_fields = ['name']
# 过滤namt或author
search_fields = ['name','author']
路由urls.py
from django.contrib import admin
from django.urls import path,include
from authenticated import views
from rest_framework import routers
router = routers.SimpleRouter()
router.register('books', views.BookView,"books")
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls))
]
访问(模糊匹配):
http://127.0.0.1:8000/books/?search=西游记
http://127.0.0.1:8000/books/?search=华
1.2 第三方过滤类
使用第三方过滤类,
第一步先安装django-filter
pip install django-filter
第二步在配置里注册settings.py
INSTALLED_APPS = [
...
'rest_framework',
'django_filters',
]
第三步在视图类中使用views.py
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from 应用名.models import Book # 数据库
from 应用名.serializer import BookSerializer # 序列化器
from django_filters.rest_framework import DjangoFilterBackend
class BookView(GenericViewSet, ListModelMixin):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_backends = [DjangoFilterBackend,]
filter_fields = ['name','author']
路由还是原来的配置。
这时访问是要过滤,关键字不能写search了,写search会把全部都打印出来,要写具体的字段名,而且后面要过滤的内容是精准匹配
http://127.0.0.1:8000/books/?name=西游记, 如果像之前直接写西则匹配不出来
http://127.0.0.1:8000/books/?name=活着&author=余华 # 这里面是and的关系,name是活着并且author是余华的
1.3 自定义过滤类
单独写一个类继承BaseFilterBackend
基类,重写filter_queryset
方法,返回queryset
对象
filter.py
from rest_framework.filters import BaseFilterBackend
class BookFilter(BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
query = request.query_params.get('name')
if query:
queryset = queryset.filter(name__contains=query)
return queryset
views.py
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from 应用名.models import Book # 数据库
from 应用名.serializer import BookSerializer # 序列化器
from 应用名.filter import BookFilter
class BookView(GenericViewSet, ListModelMixin):
queryset = Book.objects.all()
serializer_class = BookSerializer