74๐
โ
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 Q
objects:
condition = Q(full_name__icontains=s[0])
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)
๐คIsmail Badawi
13๐
Even shorter using the operator
functions and_
or or_
to combine the list of Q()
conditions
from operator import and_, or_
li = ['keith', 's', 'thompson']
Items that match all the strings (and_
)
Profile.objects.filter(reduce(and_, [Q(full_name__icontains=q) for q in li]))
Items that match any of the strings (or_
)
Profile.objects.filter(reduce(or_, [Q(full_name__icontains=q) for q in li]))
The Q()
function implements __or__()
and __and__()
to join two Q()
objects together, so they can be called using the corresponding operator
functions.
๐คC14L
- [Django]-Django. A good tutorial for Class Based Views
- [Django]-How to hide some fields in django-admin?
- [Django]-How to mock users and requests in django
2๐
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.
๐คakonsu
- [Django]-Django Rest framework, how to include '__all__' fields and a related field in ModelSerializer ?
- [Django]-How do I match the question mark character in a Django URL?
- [Django]-Trying to parse `request.body` from POST in Django
Source:stackexchange.com