对包含数组中任何值的字段过滤Django数据库 [英] Filter Django database for field containing any value in an array

查看:548
本文介绍了对包含数组中任何值的字段过滤Django数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django模型和一个表示用户全名的字段。我的客户希望我设置一个过滤器,以搜索一个用户的字符串数组,其中所有这些字符串都必须包含在全名中。



例如



如果用户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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆