利用Django实现的功能如下:
- 添加普通搜索功能
- 添加可高亮显示的搜索功能(利用whoosh库)
具体实现过程如下
1.普通搜索显示:
在views添加搜索视图函数
from django.db.models import Q
def search(request):
#获得查询关键字
q = request.GET.get('q')
error_msg = ''
if not q:
error_msg = '请输入关键词'
return render(request, 'blog/index.html', {
'error_msg':error_msg
})
post_list = Post.objects.filter(Q(title__icontains=q) | Q(body__icontains=q))
return render(request, 'blog/index.html', {
'error_msg':error_msg,
'post_list': post_list
})
在urls中添加搜索url
url(r'^search/$', views.search, name='search'),
在url中输入搜索内容进行搜索,例如:
http://127.0.0.1:8000/search/?q=静夜诗
2.高亮显示搜索内容
使用haystack和whoosh进行搜索的设置:
settings中设置安装haystack:
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
'haystack',
'blogapp.apps.BlogappConfig',
...
]
设置haystack连接的引擎和路径,设置每页显示的个数,
引擎使用的是whoosh,每页最多显示10个结果。
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'blogapp.whoosh_cn_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
},
}
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 10
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
在应用目录下创建search_indexes.py和whoosh_cn_backend.py
search_indexes.py中设置搜索的索引:
from haystack import indexes
from .models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
return Post
def index_queryset(self, using=None):
return self.get_model().objects.all()
在项目根urls中添加搜索的url:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',include('blogapp.urls')),
url(r'^', include('comments.urls')),
url(r'^search/', include(