1. 程式人生 > >django rest framework 過濾 lim分頁

django rest framework 過濾 lim分頁

一.過濾

1.首先引用diango 自帶的過濾配置

2.匯入模組

from django_filters.rest_framework import DjangoFilterBackend
from django_filters import rest_framework as filters

3.一種簡單的過濾:

class BookView(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    filter_backends 
= (DjangoFilterBackend,) filter_fields = ('title', 'price')

通過在瀏覽器後面帶上?price=100, 就可以精確過濾

 

自定義過濾

通過自己建立的過濾類來實現自定義過濾

class ProductFilter(filters.FilterSet):
    # 最小
    min_price = filters.NumberFilter(field_name="price", lookup_expr="gte")
    # 最大
    max_price = filters.NumberFilter(field_name="
price", lookup_expr="lte") # 包含 name = filters.CharFilter(field_name="title", lookup_expr="icontains") # 通過?欄位自定義過濾 class Meta: model = Book fields = ["min_price", "max_price", "name"]

BookViews

class BookView(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class 
= BookSerializer filter_backends = (DjangoFilterBackend,) # 自定義過濾類 filter_class = ProductFilter