Django学习——DRF的搜索和排序(django-filter和DRF中的SearchFilter)

一 、django-filter
1、在app中新建filters.py文件里面配置过滤器,同时将django-filter配置到setting中的apps里
2、filters.py的代码:

import django_filters
from .models import Goods


class GoodsFilter(django_filters.FilterSet):
    """
    商品的过滤类
    """
    #对商品价格设置搜索的最大最小区间
    min_price = django_filters.NumberFilter(field_name="shop_price", lookup_expr='gte')
    max_price = django_filters.NumberFilter(field_name="shop_price", lookup_expr='lte')

    class Meta:
        model = Goods
        fields = ['min_price', 'max_price']

3.views.py中得代码:

from rest_framework import generics
from rest_framework.pagination import PageNumberPagination

from goods.models import Goods
from goods.serializers import GoodsSerializer
from .filters import GoodsFilter

from rest_framework import viewsets
from rest_framework import mixins
from django_filters.rest_framework import DjangoFilterBackend

#分页的功能
class GoodsPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    page_query_param = "p"
    max_page_size = 100


class GoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    商品列表页
    """
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination
    #过滤就配置以下两行
    filter_backends = (DjangoFilterBackend,)
    filter_class = GoodsFilter

二、DRF中的SearchFilter

from rest_framework import generics
from rest_framework.pagination import PageNumberPagination

from goods.models import Goods
from goods.serializers import GoodsSerializer
from .filters import GoodsFilter

from rest_framework import viewsets
from rest_framework import mixins
from rest_framework import filters

from django_filters.rest_framework import DjangoFilterBackend


class GoodsPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    page_query_param = "p"
    max_page_size = 100


class GoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    商品列表页
    """
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination
    #只需要加上这一段代码就够了
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    search_fields = ('name', 'goods_brief', 'goods_desc')

三、排序功能:
在filter_backends字段里面加上filters.OrderingFilter

    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)

再配置一下需要按照哪些字段进行排序即可

    ordering_fields = ('sold_num', 'add_time')

你可能感兴趣的:(Django学习)