先上效果圖
附上個人網站:https://liyuankun.cn
安裝依賴庫
注意:這里我們不安裝django-haystack,因為要添加中文分詞的功能很麻煩,所以我直接集成了一個中文的django-haystack包
下載地址:https://github.com/PythonerKK/django-haystack-chinese/
pip安裝whoosh和jieba:
pip install whoosh jieba
項目配置
新建一個名為extra_apps
的目錄,把django-haystack包復制進去:
把extra_apps目錄設置為項目搜索根目錄,修改settings.py
文件
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))
添加到install_app中,修改settings.py
文件
INSTALLED_APPS = [
...
'haystack',
]
繼續修改settings.py
,添加haystack配置項
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
}
} # 每頁顯示搜索結果數目為10
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 10
# 自動生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
然后在項目的urls.py
中加入:
urlpatterns = [
...
path('search/', include('haystack.urls'))
]
集成到自己的app中
在自己的app中添加search_indexes.py文件
search_indexes.py
文件內容
from haystack import indexes
from .models import Post
class IdeaIndex(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()
在templates文件下新增一個目錄search/indexes/(你的app名)/(你的app名)_text.txt:
xxx_text.txt
這里填寫要搜索的字段名稱
{{ object.title }}
{{ object.content }}
添加后修改search.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% if query %}
<h3>搜索結果如下:</h3>
{% for result in page.object_list %}
<a href="/JiaBlog/article/{{ result.object.id }}/">{{ result.object.title }}</a><br/>
{% empty %}
<p>啥也沒找到</p>
{% endfor %}
{% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}<a href="?q={{ query }}&page={{ page.previous_page_number }}">{% endif %}« 上一頁{% if page.has_previous %}</a>{% endif %}
|
{% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% endif %}下一頁 »{% if page.has_next %}</a>{% endif %}
</div>
{% endif %}
{% endif %}
</body>
</html>
關鍵字高亮
這個非常簡單,直接在模板中引入如下字段即可
search.html
{% load highlight %}
<style>
span.highlighted {
color: red;
}
</style>
...
{% highlight query with xxx.object.title %}
如上所示,query就是代表搜索關鍵字,只需要一句代碼就可以完成高亮
重建索引
按照上述步驟,應該就能成功了,接下來我們來重建索引
python manage.py rebuild_index
運行后選擇y,然后就會提示建立索引成功
注意事項
這里必須嚴格按照這個結構創建,需要注意.txt文件名要全部小寫!!