django - 使用 Django 查询集在列中搜索多个单词

标签 django django-queryset

我有一个自动完成框,它需要返回包含输入词的结果。然而,输入词可以是部分的并且位于不同的顺序或位置。

示例:

数据库列中的值(MySQL)-

Expected quarterly sales
Sales preceding quarter
Profit preceding quarter
Sales 12 months

现在,如果用户输入 quarter sales那么它应该返回前两个结果。

我试过:
column__icontains = term  #searches only '%quarter sales% and thus gives no results
column__search = term  #searches any of complete words and also returns last result
**{'ratio_name__icontains':each_term for each_term in term.split()}   #this searches only sales as it is the last keyword argument

通过正则表达式的任何技巧,或者可能是我在 Django 中缺少的东西,因为这是一种常见的模式?

最佳答案

搜索引擎更适合此任务,但您仍然可以使用基本代码来完成。
如果您正在寻找包含“A”和“B”的字符串,您可以

Model.objects.filter(string__contains='A').filter(string__contains='B')

或者
Model.objects.filter(Q(string__contains='A') & Q(string__contains='B'))

但实际上,您最好使用配置很少的简单全文搜索引擎,例如 Haystack/Whoosh

关于django - 使用 Django 查询集在列中搜索多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10569960/

相关文章:

django PDF FileResponse "Failed to load PDF document."

Django 按日期排序,但末尾有 "None"?

python - Django 性能 |在 Django 中更新模型后重新计算所有相关模型中的字段值

python - Django 获取查询集中的范围

python - Django 查询对 ArrayFields 的长度求和

python - 查询集的高效逆向

django - docker 中主机的 localhost 和 postgres 之间的区别

python - 如何处理查询参数编码?

Python-Django 时区无法正常工作

python - 过滤数据的首选方法 models.objects.all().exclude() 或 models.objects.filter()