[英]Django models queryset with array
I want to make a function which will return applications which names contains some text. 我想制作一个函数,该函数将返回名称包含一些文本的应用程序。
Let's assume that we have below models: 假设我们有以下模型:
class Application(models.Model):
name = models.CharField(max_lenght=100)
Example values: "T2 AAA", "T2 BBB", "FSA KK" etc.
Now I want to write function which should return me application T2 AAA if attribute of this function will be AAA: 现在,我想编写一个函数,如果此函数的属性为AAA,则应返回应用程序T2 AAA:
def getApplication(request, title):
titleVars = title.split(' ')
applications = Application.objects.filter(name__in=titleVars)
Honestly I don't know how to do that, I think that I should use icontains
however I don't know how it applies to the array titleVars
. 老实说,我不知道该怎么做,我认为我应该使用icontains
但是我不知道它如何应用于数组titleVars
。
Example execution: 执行示例:
getApplication(request, 'Some text whatever T2 AAA XXX/K')
Thanks in advance 提前致谢
I think you are looking for like search. 我想您正在寻找类似的搜索。
Using Q()
- 使用Q()
-
from django.db.models import Q
obj_list = Application.objects.filter(reduce(lambda x, y: x | y, [Q(name__contains=word) for word in titleVars]))
And thats the recommended way. 那就是推荐的方法。
Other options - 其他选项-
You can do this with django-like (ref - answer ): 您可以使用django-like来做到这一点(ref- answer ):
Application.objects.filter(name__like=titleVars[1])
Other way is you can loop thru your array item, and do regex check. 其他方法是您可以遍历数组项,并进行正则表达式检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.