Django-haystack插件实现
步骤
- 安装依赖包
pip install whoosh,jieba,django-haystack
# 尽量采用其他源的pip进行安装,比如
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple django-haystack
- 将haystack加入INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
...
'post',
'haystack', #添加该行
]
- 在需要搜索的应用app下创建search_indexes.py,如在post应用下。
from haystack import indexes
from .models import Post
# 类名的命名规则是固定的,严格按照“应用名+Index”
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True,template_name='search/indexes/post/post_text.txt')
def get_model(self):
return Post
def index_queryset(self, using=None):
return self.get_model().objects.all()
将site-packages/haystack/backends/whoosh_backend.py复制到应用app下,并更名为whoosh_cn_backend.py
在settings.py中设置haystack配置
# 配置搜索设置
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'post.whoosh_cn_backend.WhooshEngine', # post应用下的whoosh_cn_backend.py文件
'PATH': os.path.join(BASE_DIR, 'whoosh_index'), # 指定了索引文件需要存放的位置,我们设置为项目根目录 BASE_DIR 下的 whoosh_index 文件夹(在建立索引时会自动创建)。
},
}
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 6 # 指定如何对搜索结果分页,这里设置为每 6 项结果为一页。
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' # 指定什么时候更新索引,这里我们使用 haystack.signals.RealtimeSignalProcessor,作用是每当有文章更新时就更新索引。由于博客文章更新不会太频繁,因此实时更新没有问题。
- 创建template/search/indexes/app_name/model_text.txt文件,建立指定的字段索引
# 如:创建template/search/indexes/post/post_text.txt
{{ object.title }}
{{ object.content }}
- 创建索引,自动生成whoosh_index文件夹
# 创建索引
python manage.py rebuild_index # 输入y即可
# 更新索引
python manage.py update_index
- 在应用app的views.py下继承SearchView
from haystack.views import SearchView
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from django.conf import settings
from django.shortcuts import render,redirect
from django.db.models import Q
class MySearchIndex(SearchView):
# template = 'search.html'
def extra_context(self):
context = super(MySearchIndex,self).extra_context()
context['category_list'] = Category.objects.all().order_by('post_category')
context['popular_post'] = Post.objects.all().order_by('-total_views')[:4]
return context
def create_response(self):
if self.request.GET.get('q'):
# print("进入not self.request")
keyword = self.request.GET.get('q')
# post_info = Post.objects.filter(title__contains=keyword)
post_info = Post.objects.filter(Q(title__icontains=keyword)|Q(content__icontains=keyword)).order_by("id") # 搜索标题和文章内容
# post_info = Post.objects.all()
paginator = Paginator(post_info, settings.HAYSTACK_SEARCH_RESULTS_PER_PAGE)
try:
page = paginator.page(int(self.request.GET.get('page', 1)))
except PageNotAnInteger:
page = paginator.page(1)
except EmptyPage:
page = paginator.page(paginator.num_pages)
context = {
'query': self.query,
'form': self.form,
'page': page,
'paginator': paginator,
'suggestion': None,
}
context.update(self.extra_context())
return render(self.request, self.template, context)
else:
qs = super(MySearchIndex, self).create_response()
# print(self.get_context())
return qs
- 在应用urls下配置路由
url(r'^search/$', MySearchIndex(), name='haystack_search'),
- 创建template/search/search.html文件
{% extends 'index.html' %}
{% block Banner %}{% endblock %}
{% block area %}
<div class="col-lg-8">
<div class="blog_left_sidebar">
<div class="row">
{% for post in page.object_list %}
<div class="col-md-6">
<article class="blog_style1 small">
<div class="blog_img">
<img class="img-fluid" style="height: 280px;" src="/media/{{ post.cover }}" alt="">
</div>
<div class="blog_text">
<div class="blog_text_inner">
<div class="cat">
<a class="cat_btn" href="#">{{ post.category }}</a>
<a href="#"><i class="fa fa-calendar" aria-hidden="true"></i> {{ post.create_time|date:"Y-m-d" }}</a>
<a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i> 05</a>
</div>
<a href="{% url 'post:detail' post.id %}" ><h4>{{ post.title }}</h4></a>
<p>{{ post.short_detail|safe }}</p>
<a class="blog_btn" href="{% url 'post:detail' post.id %}">Read More</a>
</div>
</div>
</article>
</div>
{% empty %}
<h3>没有找到相关文章</h3>
{% endfor %}
</div>
<!-- 分页栏 -->
<nav class="blog-pagination justify-content-center d-flex">
<ul class="pagination">
{% if page.has_previous %}
<li class="page-item">
<a href="{% url 'post:haystack_search' %}?q={{ query }}&page={{ page.previous_page_number }}" class="page-link" aria-label="Previous">
<span aria-hidden="true">
<span class="lnr lnr-chevron-left"></span>
</span>
</a>
</li>
{% else %}
<li class="page-item">
<a href="#" class="page-link" aria-label="Previous">
<span aria-hidden="true">
<span class="lnr lnr-chevron-left"></span>
</span>
</a>
</li>
{% endif %}
{% for num in page.paginator.page_range %}
{% if num == page.number %}
<li class="page-item active"><a href="{% url 'post:haystack_search' %}?q={{ query }}&page={{ num }}" class="page-link">{{ num }}</a></li>
{% else %}
<li class="page-item"><a href="{% url 'post:haystack_search' %}?q={{ query }}&page={{ num }}" class="page-link">{{ num }}</a></li>
{% endif %}
{% endfor %}
{% if page.has_next %}
<li class="page-item">
<a href="{% url 'post:haystack_search' %}?q={{ query }}&page={{ page.next_page_number }}" class="page-link" aria-label="Next">
<span aria-hidden="true">
<span class="lnr lnr-chevron-right"></span>
</span>
</a>
</li>
{% else %}
<li class="page-item">
<a href="#" class="page-link" aria-label="Next">
<span aria-hidden="true">
<span class="lnr lnr-chevron-right"></span>
</span>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
</div>
{% endblock %}
网上示例需要在字段选取中间加个object,如:
<p>{{ post.object.short_detail|safe }}</p>
项目文件结构
异常解决
- ImportError: cannot import name 'six' from 'django.utils'
- 安装six
pip install six
- 将six.py复制到django/utils
文件路径
site-packages/six.py
site-packages/django/utils
- ImportError: cannot import name python_2_unicode_compatible
- 报错位置导入的包替代为以下导入语句
from django.utils.six import python_2_unicode_compatible