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 restful framework 中的 filter 自定义过滤)