亲宝软件园·资讯

展开

Django rest framework过滤器 Django-rest-framework中过滤器的定制实例

axon-缪 人气:0

1、定义一个自定义的filter.py模块,增加一个新的过滤类

import django_filters
#这个Q可以支持表查询,单下划线获取表字段,双下划线获取关联表,
from django.db.models import Q
#引入自己的模型
from app.item.models import ItemCategory
#自定义的过滤类,需要继承django_filter.rest_framework中的FilterSet类
class ItemCategoryFilter(django_filters.rest_framework.FilterSet):
  Filter_category = django_filters.NumberFilter(method='category_filter', label='Filter_category')
  #django_filters.NumberFilter类似,ModelForm中字段类型的控制
  #其中method指向自己定义的过滤函数,label用于标识在测试API界面中的过滤界面字段,Filter_category控制查询字段
  def category_filter(self, queryset, name, value):
    #这里用到多级联表查询
    return queryset.filter(Q(category_id=value)|Q(category__parent_id=value)|Q(category__parent__parent_id=value)|Q(category__parent__parent__parent_id=value))
  class Meta:
    model = ItemCategory
    fields = []

2、将视图处理类中的,过滤器后端重新指定,将过滤器类连接到我们自定义实现的处理类上

class ItemsListByCategory(generics.ListCreateAPIView):
  '''
    根据category编号获取相关模型no。
    请求中请带有参数category
    @:require param: category
    such as: GET /itemsListByCategory/?Filter_category=2
  '''
  from django_filters.rest_framework import DjangoFilterBackend
  from app.item.filters import ItemCategoryFilter

  queryset = ItemCategory.objects.all()
  serializer_class = ItemCategorySerializer
  pagination_class = CommonPagination
  # 在这里哦
  filter_backends = (DjangoFilterBackend,)
  filter_class =ItemCategoryFilter
  permission_classes = (ReadOnly,)

补充知识:Django restful framework 中的 filter 自定义过滤

class AlertFilter(django_filters.rest_framework.FilterSet):
  
   .......
  to_bearer_service = django_filters.rest_framework.CharFilter(method='to_bearer_service_filter', label='bearer_service')

  class Meta:
    model = Alert
    fields = [......, 'to_bearer_service']

  @staticmethod  # 如果想获取请求信息可以去掉这个静态方法的装饰器,为什么要加静态方法装饰器我也不清楚
  def to_bearer_service_filter(queryset, name, value):
    Q_id = Q()
    for i in value.split(","):
      if i == "0":
        Q_id.add(Q(**{'to_bearer_service':None}), Q.OR)
      else:
        Q_id.add(Q(**{'to_bearer_service_id': int(i)}), Q.OR)
    queryset = queryset.filter(Q_id)
    return queryset
 
 
  def to_bearer_service_filter(self, queryset, name, value):
    Q_id = Q()
    for i in value.split(","):
      if i == "0":
        Q_id.add(Q(**{'to_bearer_service':None}), Q.OR)
      else:
        Q_id.add(Q(**{'to_bearer_service_id': int(i)}), Q.OR)
    queryset = queryset.filter(Q_id)
    return queryset

以上这篇Django-rest-framework中过滤器的定制实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论