在没有第 3 方应用的情况下搜索 django 模型的多个字段 [英] Search multiple fields of django model without 3rd party app

查看:21
本文介绍了在没有第 3 方应用的情况下搜索 django 模型的多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 django 应用程序中有一个模型,我想为其创建一个搜索表单.有没有办法使用相同的搜索字符串一次搜索模型中的所有字段?我已经研究过 xapian 和 solr,但它们似乎搜索超过 1 个模型的开销很大.我希望能够这样说:

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.

推荐答案

一旦您拥有所有字段名称,您就可以创建 Q 对象 使用 kwarg 扩展 并使用reduce()operator.or_ 将它们转换为单个查询.

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)

这篇关于在没有第 3 方应用的情况下搜索 django 模型的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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