在apps/news/search_indexes.py中创建如下类:(名称固定为search_indexes.py)
# -*-# -*- coding: utf-8 -*- # 斌彬电脑 # @Time : 2018/10/12 0012 8:47 from haystack import indexes # from haystack import site from .models import News class NewsIndex(indexes.SearchIndex, indexes.Indexable): """ News索引数据模型 类 """ text = indexes.CharField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') title = indexes.CharField(model_attr='title') digest = indexes.CharField(model_attr='digest') content = indexes.CharField(model_attr='content') image_url = indexes.CharField(model_attr='image_url') # comments = indexes.IntegerField(model_attr='comments') def get_model(self): """ 返回建立索引的模型类 """ return News def index_queryset(self, using=None): """ 返回要建立索引的数据查询集 :param using: :return: """ # 条件:把未被逻辑删除的,进行搜索 return self.get_model().objects.filter(is_delete=False, tag_id=1) # return self.get_model().objects.filter(is_delete=False, tag_id__in=[1, 2, 3, 4, 5, 6])
后台视图
from haystack.views import SearchView as _SearchView class SearchView(_SearchView): # 模版文件 template = 'news/search.html' # 重写响应方式,如果请求参数q为空,返回模型News的热门新闻数据,否则根据参数q搜索相关数据 def create_response(self): kw = self.request.GET.get('q', '') if not kw: show_all = True hot_news = models.HotNews.objects.select_related('news'). only('news__title', 'news__image_url', 'news__id'). filter(is_delete=False).order_by('priority', '-news__clicks') paginator = Paginator(hot_news, settings.HAYSTACK_SEARCH_RESULTS_PER_PAGE) try: page = paginator.page(int(self.request.GET.get('page', 1))) except PageNotAnInteger: # 如果参数page的数据类型不是整型,则返回第一页数据 page = paginator.page(1) except EmptyPage: # 用户访问的页数大于实际页数,则返回最后一页的数据 page = paginator.page(paginator.num_pages) return render(self.request, self.template, locals()) else: show_all = False qs = super(SearchView, self).create_response() return qs
在apps/news/urls.py中
urlpatterns = [
path('search/', views.SearchView(), name='search'),
]
创建templates/search/indexes/news/news_text.txt文件(文件名为:应用名_text.txt)
{{ object.title }}
{{ object.digest }}
{{ object.content }}
templates/search/indexes,为固定路径,不可更改,
/news/news_text.txt 与应用名,模型名相关,
把要搜索的字段,填入该文件中,
手动创建 索引表:
进入虚拟环境:
workon mayun
进入到项目:
cd myblog/
(mayun) binbin@abc:~/myblog/myblog$ ls
a apps db.sqlite3 __init__.py logs manage.py media myblog MyBlog_Static templates utils
重建索引: python manage.py rebuild_index
执行命令:
python manage.py haystack_info
会帮我们创建索引表:
Number of handled 1 index(es).
- Model: News by Index: <apps.news.search_indexes.NewsIndex object at 0x7f8b99c5fb88>
手动更新: python manage.py update_index