Filter multiple fields using single input

Viewed 73

My backend in Python :

def resview(request, *args, **kwargs):
    if 'uid' not in kwargs:
        kwargs = kwargs.copy()
        kwargs['filter'] = {}

        username = request.GET.get('username')
        if username:
            kwargs['filter']['user__username__contains'] = username

    return resource_view(request, UserProfile, get_userprof, put_userprof,
        deleter=del_userprof, api=request.api, order_by='user__username', **kwargs)

I can successfully search for the username but I want to be able to search on multiple fields with a single input and I don't know how to do it.

3 Answers

I have once in similar situation used Regular Expression to search based on keywords & then pulling out entire line until newline. Here I'm mentioning my small code.

Step1: Save the content in Text file

str = open('file.txt', 'r').read()
import re

#to print id

m = re.search('(?<=id: )(.*)', str)
print ("id= " , (m.groups()))

#to print username
m = re.search('(?<=username: )(.*)', str)
print (username= " , (m.groups()))
############
#and so on----Replace keywords whatever you need...
#############

You can store the JSON list in a list variable and filter the results.

filterData(searchString){

   searchString = searchString.trim();
    
   return this.data.filter(user=> user.username.toLowerCase().indexOf(searchString.toLowerCase()) !== -1 || user.firstname.toLowerCase().indexOf(searchString.toLowerCase()) !== -1 || user.lastname.toLowerCase().indexOf(searchString.toLowerCase()) !== -1);
     
}

I suggest that you use two different lists to save data. One filtered and the other un filtered. This way you won't have to call the service again to get original data. Filter is always applied on unfiltered data.

Considering you're using django, I would suggest to take look at SearchFilter which supports searching multiple fields at once.

Beside of that, you can filter queryset by hands with custom implementation of Filter:

class F(django_filters.FilterSet):
    username = CharFilter(method='my_custom_filter')

    class Meta:
        model = User
        fields = ['username', 'firstname', 'lastname', 'email']

    def my_custom_filter(self, queryset, name, value):
        return queryset.filter(
            Q(username__ilike=value) 
            | Q(firstname__ilike=value)
            | Q(lastname__ilike=value) 
            | Q(email__ilike=value)
        )
Related