在没有第三方应用的情况下搜索django模型的多个字段 [英] Search multiple fields of django model without 3rd party app
问题描述
results = Assignment.objects.filter(any_column = search_string)
我意识到可能没有一些简明扼要的东西,但现在唯一可以使用搜索功能的选项应用程序是单独检查每个字段,并将结果连接在一起。
一旦你拥有所有的域名,您可以创建 Q
对象使用 kwarg expansion ,并使用 reduce()
以及 operator.or _
将它们变成单个查询。
$ b $对于字段名称中的字段名称,b
qgroup = reduce(operator.or_,(Q(** {fieldname:value}))
asgns = Assignment.objects.filter qgroup)
I have a single model in my django app that I want to create a search form for. Is there a way to search all the fields in the model at once with the same search string? I've looked into xapian and solr but they seem like a lot of overhead for searching over 1 model. I want to be able to say something like:
results = Assignment.objects.filter(any_column = search_string)
I realize there might not be something that concise but right now the only option I can come up with other than using a search app is to check each field separately and concatenate the results together.
Once you have all the field names you can create Q
objects using kwarg expansion and use reduce()
along with operator.or_
to turn them into a single query.
qgroup = reduce(operator.or_, (Q(**{fieldname: value}) for fieldname in fieldnames))
asgns = Assignment.objects.filter(qgroup)
这篇关于在没有第三方应用的情况下搜索django模型的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!