安装haystack和Whoosh
pip install drf-haystack
pip install whoosh
pip install jieba # Whoosh只支持英文分词搜索,不支持中文的分词,所以我们需要使用Jieba进行中文分词
django-haystack的配置 Whoosh搜索引擎
修改settings.py文件,添加haystack应用:
INSTALLED_APPS = (
...
'haystack', #将haystack放在最后
)
在settings中追加haystack的相关配置:
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
}
}
# 添加此项,当数据库改变时,会自动更新索引,非常方便
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
在应用目录下,添加一个索引类
在子应用的目录下,创建一个名为 search_indexes.py 的文件。
from haystack import indexes
① # 修改此处,改成你自己的model
from goods.models import Goods (Goods是子应用goods中的一个模型类)
② #修改此处,类名为模型类的名称+Index,比如模型类为Goods,则这里类名为GoodsIndex
class GoodsIndex(indexes.SearchIndex, indexes.Indexable):