DRF之过滤

五个接口中,只有获取所有需要过滤,其他不需要

内置过滤

  导入

from rest_framework.filters import SearchFilter

  在视图类中写

from .models import Book
from .serizlizer import BookSerizlizer
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ViewSetMixin, GenericViewSet
from rest_framework.filters import SearchFilter
from rest_framework.mixins import ListModelMixin


# class BookView(ViewSetMixin, ListAPIView):
class BookView(GenericViewSet, ListModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerizlizer
    filter_backends = [SearchFilter, ]
    search_fields = ['name', 'author']



# 在视图类中
# 必须继承GenericAPIView,才有这个类属性
filter_backends = [SearchFilter,]
# 需要配合一个类属性,可以按name过滤
search_fields=['name','author']

  搜索时候是模糊查询

http://127.0.0.1:8000/books/?search=花
http://127.0.0.1:8000/books/?search=花  # 书名或者author中带花就能搜到

 第三方过滤类

  安装

pip3 install django-filter

  注册

INSTALLED_APPS = [
        。。。
    'django_filters',
]

  导入过滤类

from django_filters.rest_framework import DjangoFilterBackend

  在视图类中使用

from django_filters.rest_framework import DjangoFilterBackend


class BookView(GenericViewSet, ListModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerizlizer
 
    filter_backends = [DjangoFilterBackend, ]
 
    filter_fields = ['name']



class BookView(GenericViewSet,ListModelMixin):
    # 必须继承GenericAPIView,才有这个类属性
    filter_backends = [DjangoFilterBackend,]
    # 需要配合一个类属性
    filter_fields=['name','author']

  查询方式

http://127.0.0.1:8000/books/?name=红楼梦
http://127.0.0.1:8000/books/?name=红楼梦&author=小明  # and条件
http://127.0.0.1:8000/books/?author=小明

 自定义过滤

  写一个类,继承BaseFilterBackend 基类,重写filter_queryset方法,返回qs对象,是过滤后的对象

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.filter(name__contains=query)
        return queryset

  在视图类中使用

from .filter import BookFilter


class BookView(GenericViewSet, ListModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerizlizer
    filter_backends = [BookFilter, ]

  查询方式

http://127.0.0.1:8000/books/?name=红  # 模糊匹配 ,自己定义的

 

posted @ 2022-04-06 22:33  那就凑个整吧  阅读(85)  评论(0编辑  收藏  举报