2017-05-26 92 views
0

我有自定義過濾器,以我的視圖集:如何從多個領域進行搜索?

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中搜索包含搜索字符串的數據。怎麼做?

回答

2

對於無法用單個過濾器表示的複雜行爲,一般都會使用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))