全局搜索

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 %}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值