1,下载django-haystack
pip install django-haystack
2,注册应用
‘ haystack ’,
3,配置whoosh搜索引擎(在主应用settings.py下方)
HAYSTACK_CONNECTIONS = {
'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': BASE_DIR / 'whoosh_index'
},
}
4,在应用(需要检索)应用下方新建search_indexes.py
内容为:
from haystack import indexes
from .models import News(模型名)
class NewsIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
return News
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.all()
5,新建搜索模板 项目下方templates中创建嵌套文件夹
templates/ search /indexes / myapp / 应用名_text.txt
在 应用名_text.txt 写可以用来检索的内容:{{ object.title }}
{{ object.content}}
6,在项目路由下添加 path('search/',include('haystack.urls')),
7,设置搜索结果模板(搜索成功后的html页面)
(1)在 templates 下方 search 文件夹下方创建 search.html文件
(2)内容:
{% extends 'base.html' %}
{% block title %}
<title> 新闻网搜索结果 </title>
{% endblock %}
{% block main %}
{% if query %}
<h3>搜索结果</h3>
{% for result in page.object_list %}
<p>
<a href="{% url 'news:detail' result.object.id %}">{{ result.object.title }}</a>
</p>
{% endfor %}
{% endif %}
{% endblock %}
8,安装whoosh
pip install whoosh
9,使用jieba 中文分词
(1)下载jieba:pip install jiaba
(2)配置使用中文检索:
(2.1)将haystack.backends.whoosh_backend的内容复制应用下方 改名为whoosh_cn_backend
(2.2) 替换47行内容:from jieba.analyse import ChineseAnalyzer
(2.3)替换232行内容: analyzer=field_class.analyzer orChineseAnalyzer(),
(2.4)替换793行内容: sa = ChineseAnalyzer()
10,从新配置引擎
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': '应用名.whoosh_cn_backend.WhooshEngine',
'PATH': BASE_DIR / 'whoosh_index',
},
}
11,针对内容构建索引
python .\manage.py rebuild_index
12, 配置搜索表单
(1)action = '/search/’
(2)method = 'get'
(3) name = " q "
注:固定不可变
<form class="navbar-form navbar-left" action="/search/" method="get">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="输入搜索内容">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>