与DRF集成自定义fliter
2020-06-01 本文已影响0人
北海鲸落
主要目的:使用filter完成模糊查询
1. 使用FilterSet
- 执行
pip install django_filter
命令 - 导入
from django_filters import rest_framework as filters
- 使用
FilterSet
- 将其添加到
filterset_class
视图类的参数中 - 使用新的
FilterSet
时,仅需要更改导入路径 - 如果要默认使用
django-filter
后端,请将其添加到DEFAULT_FILTER_BACKENDS
设置中。
# settings.py
INSTALLED_APPS = [
...
'rest_framework',
'django_filters',
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
...
),
}
实现代码
from rest_framework import generics
from django_filters import rest_framework as filters
from myapp import Product
class ProductFilter(filters.FilterSet):
min_price = filters.NumberFilter(field_name="price", lookup_expr='gte')
max_price = filters.NumberFilter(field_name="price", lookup_expr='lte')
class Meta:
model = Product
fields = ['category', 'in_stock', 'min_price', 'max_price']
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [filters.DjangoFilterBackend,]
filterset_class = ProductFilter
2. 使用 filterset_fields
filterset_fields
和FilterSet
不可同时使用
实例代码
from rest_framework import generics
from django_filters import rest_framework as filters
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
filter_backends = (filters.DjangoFilterBackend,)
filterset_fields = ('category', 'in_stock')