How to search from many fields?

2019-07-22 14:18发布

问题:

I have custom filter to my viewset:

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']

And it works when I send query like this:

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

or

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

but I want to create only one query to search data containing search string in username, first_name and last_name. How to do it?

回答1:

The general catch-all for complicated behavior that can't be expressed by a single filter is to use the method argument to a filter class (docs).

A possible implementation:

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))