1. 程式人生 > 其它 >DRF之過濾

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=紅  # 模糊匹配 ,自己定義的