1、安装模块
pip install django-haystack
pip install whoosh
pip install jieba
2、在settings中添加应用
INSTALLED_APPS = [
'haystack'
]
3、引入全文检索路由
urls.py中添加代码
from haystack.views import SearchView
urlpatterns = [
url('search/',SearchView(),name='search'),
]
4、创建索引类
在应用目录下方新建search_indexes.py
from haystack import indexes
from .models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
return Post
def index_queryset(self, using=None):
return self.get_model().objects.all()
5、设置数据模板
在目录“templates/search/indexes/应用名称/”下创建“模型类名称_text.txt”文件,这里列出了要对哪些列的内容进行检索
{{object.title}}
{{object.summary}}
{{object.body}}
6、配置搜索引擎与jieba分词
复制Lib\site-packages\haystack\backends\whoosh_backend.py文件, 粘贴到应用目录下(这里是blog) 改名为whoosh_cn_backend.py
from jieba.analyse import ChineseAnalyzer
查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()
在settings中配置
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 应用名.whoosh_cn_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
}
}
# 配置搜索结果分页
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 10
# 配置索引实时更新
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
7、新建搜索表单
name="q"不能修改
<form role="search" method="get" id="searchform" action="/search/">
<input type="search" placeholder="搜索" required name="q">
<button type="submit"><span class="ion-ios-search-strong"></span></button>
</form>
8、搜索结果页面
在templates/search目录新建search.html
{% if query %}
{% for post in page.object_list %}
<li>{{post.object.title}}</li>
{% empty %}
没有找到内容
{% endfor %}
{% endif %}