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

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

问题描述

我在我的django应用程序中有一个模型,我想创建一个搜索表单。有没有办法使用相同的搜索字符串一次搜索模型中的所有字段?我已经研究了xapian和solr,但是它们似乎在搜索超过1个模型时有很多开销。我想能够说出这样的东西:

  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屋!

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