如何从许多领域搜索?

时间:2017-05-26 16:04:36

标签: django-rest-framework django-filter

我有自定义过滤器到我的视图集:

class OrderFilter(django_filters.rest_framework.FilterSet):
    username = django_filters.CharFilter(name='user__username', lookup_expr='icontains')
    client_name = django_filters.CharFilter(name='user__first_name', lookup_expr='icontains')

    class Meta:
        model = Order
        exclude = ['pk']

当我发送这样的查询时它会起作用:

http://localhost:8000/orders/?username=testuser

http://localhost:8000/orders/?client_name=john

但我想只创建一个查询来搜索usernamefirst_namelast_name中包含搜索字符串的数据。怎么做?

1 个答案:

答案 0 :(得分:4)

单个过滤器无法表达的复杂行为的一般性问题是将method参数用于过滤器类(docs)。

可能的实施:

from django_filters import rest_framework as filters
from django.db.models import Q


class OrderFilter(filters.FilterSet):
    search = filters.CharFilter(method='search_filter')

    def search_filter(self, queryset, name, value):
        return queryset.filter(Q(username__icontains=value) 
                               | Q(first_name__icontains=value) 
                               | Q(last_name__icontains=value))