对包含数组中任何值的字段过滤Django数据库 [英] Filter Django database for field containing any value in an array
问题描述
例如
如果用户full_name =Keith,汤姆森S。
我有一个列表['keith','s','thomson']
我想执行相当于
< p $ p>
Profile.objects.filter(full_name__icontains ='keith',full_name__icontains ='s',full_name__icontains ='thomson')
问题是这个列表可以是动态大小 - 所以我不知道该怎么做。
任何人有任何想法?
连续调用 filter
:
queryset = Profile.objects.all()
strings = ['keith','s' thompson']
字符串中的字符串:
queryset = queryset.filter(full_name__iconta ins = string)
或者您可以&
一起一堆 Q
对象:
condition = Q(full_name__icontains = s [0])
字符串中的字符串[1:]:
条件& = Q(full_name__icontains = string)
queryset = Profile.objects.filter(condition)
写一个更隐秘的方式,避免显式循环:
import operator
#...
condition = reduce(operator.and_,[Q(full_name__icontains = s)for s in strings])
queryset = Profile.objects.filter(condition)
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.
For example
If a users full_name = "Keith, Thomson S.".
And I have a list ['keith','s','thomson']
I want to perform the filter equivalent of
Profile.objects.filter(full_name__icontains='keith',full_name__icontains='s',full_name__icontains='thomson')
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 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)
这篇关于对包含数组中任何值的字段过滤Django数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!