博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django简单博客实战(六)---搜索功能
阅读量:3924 次
发布时间:2019-05-23

本文共 4909 字,大约阅读时间需要 16 分钟。

Django-haystack插件实现

项目地址:https://github.com/ylpxzx/lifeblog

步骤

  1. 安装依赖包
pip install whoosh,jieba,django-haystack# 尽量采用其他源的pip进行安装,比如pip install -i https://pypi.tuna.tsinghua.edu.cn/simple django-haystack
  1. 将haystack加入INSTALLED_APPS
INSTALLED_APPS = [    'django.contrib.admin',	...	'post',    'haystack',   #添加该行]
  1. 在需要搜索的应用app下创建search_indexes.py,如在post应用下。
from haystack import indexesfrom .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()
  1. 将site-packages/haystack/backends/whoosh_backend.py复制到应用app下,并更名为whoosh_cn_backend.py

  2. 在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,作用是每当有文章更新时就更新索引。由于博客文章更新不会太频繁,因此实时更新没有问题。
  1. 创建template/search/indexes/app_name/model_text.txt文件,建立指定的字段索引
# 如:创建template/search/indexes/post/post_text.txt{
{
object.title }}{
{
object.content }}
  1. 创建索引,自动生成whoosh_index文件夹
# 创建索引python manage.py rebuild_index  # 输入y即可# 更新索引python manage.py update_index
  1. 在应用app的views.py下继承SearchView
from haystack.views import SearchViewfrom django.core.paginator import Paginator,EmptyPage,PageNotAnIntegerfrom django.conf import settingsfrom django.shortcuts import render,redirectfrom django.db.models import Qclass 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
  1. 在应用urls下配置路由
url(r'^search/$', MySearchIndex(), name='haystack_search'),
  1. 创建template/search/search.html文件
{
% extends 'index.html' %}{
% block Banner %}{
% endblock %}{
% block area %}
{
% for post in page.object_list %}
{
% empty %}

没有找到相关文章

{
% endfor %}
{
% endblock %}

网上示例需要在字段选取中间加个object,如:

{

{
post.object.short_detail|safe }}

项目文件结构

在这里插入图片描述


异常解决

  • ImportError: cannot import name ‘six’ from ‘django.utils’
  1. 安装six
pip install six
  1. 将six.py复制到django/utils

文件路径

site-packages/six.py

site-packages/django/utils

  • ImportError: cannot import name python_2_unicode_compatible
  1. 报错位置导入的包替代为以下导入语句
from django.utils.six import python_2_unicode_compatible

转载地址:http://cgugn.baihongyu.com/

你可能感兴趣的文章
Leetcode 110. 平衡二叉树
查看>>
Leetcode 111. 二叉树的最小深度
查看>>
Leetcode 226. 翻转二叉树
查看>>
Leetcode 617. 合并二叉树
查看>>
Leetcode 654. 最大二叉树
查看>>
Leetcode 304. 二维区域和检索 - 矩阵不可变
查看>>
Leetcode 45. 跳跃游戏 II
查看>>
模式2. 工厂方法模式-Java
查看>>
模式1. 简单工厂模式-Java
查看>>
模式6.原型模式-Java
查看>>
Leetcode 146. LRU 缓存机制
查看>>
Leetcode 208. 实现 Trie (前缀树)
查看>>
Leetcode 1114. 按序打印
查看>>
kill -15、kill -9 与 kill
查看>>
剑指 Offer 05. 替换空格
查看>>
剑指 Offer 06. 从尾到头打印链表
查看>>
模式9.建造者模式-Java
查看>>
模式11. 抽象工厂模式-Java
查看>>
模式10. 观察者模式-Java
查看>>
剑指 Offer 09. 用两个栈实现队列
查看>>