如何在Django搜索字段中指定多个列名?

时间:2017-07-10 12:49:12

标签: django-rest-framework filtering

我使用django过滤后端 我在搜索字段中定义了多个列,如下所示:

class tableViewSet(ModelViewSet):
    """
    A simple ViewSet for viewing and editing accounts.
    """
    queryset = table.objects.all()
    serializer_class = WebSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = (DjangoFilterBackend,SearchFilter)
    search_fields = ('name','family','tel',)

我想创建一个api来处理这样的查询:    从table1中选择*,其中名称如(&#39; tom&#39;)和家人一样(&#39;%anderson%&#39;)和tel like(&#39;%0223654%&#39;)< / p>

有没有办法在API中指定列名?

例如:

http://127.0.0.1/api-user/table/search?name=tom&family=andeson&tel=0223455

2 个答案:

答案 0 :(得分:0)

不需要在查询字符串中指定字段。以下请求应该有效:

http://127.0.0.1/api-user/table?search=something

relevant docs

答案 1 :(得分:0)

如果您想根据特定属性进行过滤,则应该使用DjangoFilterBackend代替SearchFilter

由于您不是在寻找精确搜索,因此您必须在视图中创建FilterSet并使用filter_class

类似的东西:

class TableFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(name='name', lookup_expr='icontains')
    family = django_filters.CharFilter(name='family', lookup_expr='icontains')
    tel = django_filters.CharFilter(name='tel', lookup_expr='icontains')

    class Meta:
        model = table
        fields = ['name', 'family', 'tel']

class tableViewSet(ModelViewSet):
    """
    A simple ViewSet for viewing and editing accounts.
    """
    queryset = table.objects.all()
    serializer_class = WebSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = (DjangoFilterBackend,SearchFilter)
    filter_class = TableFilter