安装
pip install django-haystack
pip install whoosh
配置
#1.需要在settings里面添加haystack实例名字 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'haystack' ] #2.在settings里添加如下内容 HAYSTACK_CONNECTIONS = { 'default': { #设置haystack搜索引擎 'ENGINE':'haystack.backends.whoosh_backend.WhooshEngine', #设置索引文件位置 'PATH': os.path.join(BASE_DIR,'whoosh_index'), } }
创建索引类
在模型所属的app下创建一个search_indexes.py文件,然后创建索引类,比如要给news创建索引,代码如下:
from haystack import indexes class NewsIndex(indexes.SearchIndex.indexes.Indexable): #创建索引字段(最好叫text) text = indexes.CharField(document=True,use_template=True) def get_model(self): return News def index_queryset(self, using=None): return self.get_model().objects.all()