一、django_filter
官网地址:https://django-filter.readthedocs.io/en/master/
- settings.py
INSTALLED_APPS = [
...
'django_filters',
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
- views.py
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from . import models
from .serializers import GoodsSerializer
class GoodsPagination(PageNumberPagination):
page_size = 2
max_page_size = 100
# 自动返回第n页
page_query_param = "p"
# 自动返回n页
page_size_query_param = 'page_size'
class GoodsList(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
"""
queryset = models.Goods.objects.get_queryset()
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
filter_backends = (DjangoFilterBackend,)
filterset_fields = ('name', 'market_price')
-
展示
优化
自定义filters.py
from . import models
from django_filters import rest_framework as filters
class GoodsFilter(filters.FilterSet):
"""商品过滤类"""
# 商品名模糊搜索
name = filters.CharFilter(field_name="name", lookup_expr="icontains")
# 最小值
min_price = filters.NumberFilter(field_name="market_price", lookup_expr='gte')
# 最大值
max_price = filters.NumberFilter(field_name="market_price", lookup_expr='lte')
class Meta:
model = models.Goods
fields = ['name','min_price', 'max_price']
# views.py
from django_filters.rest_framework import DjangoFilterBackend
from goods.filters import GoodsFilter
filter_backends = (DjangoFilterBackend,)
filter_class = GoodsFilter
searchFilter
https://www.django-rest-framework.org/api-guide/filtering/#searchfilter
from rest_framework import viewsets
from rest_framework import filters
from . import models
from .serializers import GoodsSerializer
class GoodsList(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
"""
queryset = models.Goods.objects.get_queryset()
serializer_class = GoodsSerializer
# 通用字段搜索 + search搜索
filter_backends = (filters.SearchFilter)
search_fields = ('name', 'marker_price')
# '='精确搜索
search_fields = ('=name', 'marker_price')
-
展示
三、OrderFilter
from rest_framework import viewsets
from rest_framework import filters
from . import models
from .serializers import GoodsSerializer
class GoodsList(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
"""
queryset = models.Goods.objects.get_queryset()
serializer_class = GoodsSerializer
# search搜索 + order 排序
filter_backends = (filters.SearchFilter, filters.OrderingFilter,)
search_fields = ('name', 'market_price')
# 排序字段
ordering_fields = ('sold_num', 'market_price')
-
展示