Each Answer to this Q is separated by one/two green lines.
I have a django model and a field representing a users full name. My client wants me to set up a filter to search for a user based on an array of strings where all of them have to be case insensitive contained within the full name.
If a users
full_name = "Keith, Thomson S."
And I have a list
I want to perform the filter equivalent of
The problem is this list can be of dynamic size – so I do not know how to do this.
Anyone have any ideas?
Make successive calls to
filter, like so:
queryset = Profile.objects.all() strings = ['keith', 's', 'thompson'] for string in strings: queryset = queryset.filter(full_name__icontains=string)
Alternatively you can
& together a bunch of
condition = Q(full_name__icontains=s) for string in strings[1:]: condition &= Q(full_name__icontains=string) queryset = Profile.objects.filter(condition)
A more cryptic way of writing this, avoiding the explicit loop:
import operator # ... condition = reduce(operator.and_, [Q(full_name__icontains=s) for s in strings]) queryset = Profile.objects.filter(condition)
Even shorter using the
or_ to combine the list of
from operator import and_, or_ li = ['keith', 's', 'thompson']
Items that match all the strings (
Profile.objects.filter(reduce(and_, [Q(full_name__icontains=q) for q in li]))
Items that match any of the strings (
Profile.objects.filter(reduce(or_, [Q(full_name__icontains=q) for q in li]))
Q() function implements
__and__() to join two
Q() objects together, so they can be called using the corresponding
something along these lines:
array = ['keith', 's', 'thomson'] regex = '^.*(%s).*$' % '|'.join(array) Profile.objects.filter(full_name__iregex=regex)
EDIT: this is wrong, the OP wants names which contain all strings simultaneously.