Django REST framework (十三)django-filter过滤使用

  • A+
所属分类:Django REST framework

官网:https://django-filter.readthedocs.io/en/master/guide/rest_framework.html

安装

pip install django-filter

导入:

setting.py

INSTALLED_APPS = [
     ......
    'django_filters' #导入项目
]
REST_FRAMEWORK = {
    # 设置全局过滤器,也可以针对每个views导入
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}

使用:

第一种直接使用filterset_fields

from django_filters import rest_framework as filters

class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_fields = ('category', 'in_stock')

第二种使用filterset_class

# 定义filterset_class 
from django_filters import rest_framework as filters
from .models import *

class PushHostUserAuthorizedFilter(filters.FilterSet):
    id = filters.CharFilter(field_name='id', lookup_expr='icontains')
    secret_id = filters.CharFilter(field_name='secret__id', lookup_expr='exact')
    publicIP = filters.CharFilter(field_name='pushhostuser__pushhost__public', lookup_expr='icontains')
    #接口请求的明                  field_name: 字段名,关联字段用__下划线          lookup_expr:匹配方式
    class Meta:
        model = PushHostUserAuthorized
        fields = ('id', 'secret_id' ,"publicIP")
#使用
class PushHostUserAuthorizedViewSet(ReadOnlyModelViewSet):
    queryset = PushHostUserAuthorized.objects.all()
    serializer_class = PushHostUserAuthorizedSerializer
    permission_classes = (IsAdminUser,)
    filter_backends = (DjangoFilterBackend,)
    filterset_class = PushHostUserAuthorizedFilter #使用cliass的filter

注意:filterset_fields和filterset_class不能再一个views共用

lookup_expr讲解:

lookup_expr='icontains': 模糊匹配,搜索条件里面包含了对应的东西就匹配lookup_expr='exact': 必须和搜索条件一致

其他具体的https://docs.djangoproject.com/en/3.0/ref/models/querysets/#field-lookups

访问:

http://127.0.0.1:8000/api/PushHostUserAuthorizedFilter?secret_id =123

Django REST framework (十三)django-filter过滤使用
  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin
广告也精彩

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: