美文网首页程序员
与DRF集成自定义fliter

与DRF集成自定义fliter

作者: 北海鲸落 | 来源:发表于2020-06-01 09:03 被阅读0次

    主要目的:使用filter完成模糊查询

    1. 使用FilterSet

    1. 执行pip install django_filter命令
    2. 导入
    from django_filters import rest_framework as filters
    
    1. 使用FilterSet
    2. 将其添加到filterset_class视图类的参数中
    3. 使用新的FilterSet时,仅需要更改导入路径
    4. 如果要默认使用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_fieldsFilterSet不可同时使用

    实例代码

    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')
    

    相关文章

      网友评论

        本文标题:与DRF集成自定义fliter

        本文链接:https://www.haomeiwen.com/subject/gecjzhtx.html