pip install django-haystack pip install whoosh pip install jieba
INSTALLED_APPS = ( ... 'haystack', #将haystack放在最后 )
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
}
}
# 添加此项,当数据库改变时,会自动更新索引,非常方便
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
urlpatterns = [
...
url(r'^search/', include('haystack.urls')),
]
from haystack import indexes
# 修改此处,为你自己的model
from models import GoodsInfo
# 修改此处,类名为模型类的名称+Index,比如模型类为GoodsInfo,则这里类名为GoodsInfoIndex
class GoodsInfoIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
# 修改此处,为你自己的model
return GoodsInfo
def index_queryset(self, using=None):
return self.get_model().objects.all()
{{ object.字段1 }}
{{ object.字段2 }}
{{ object.字段3 }}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% if query %}
<h3>搜索结果如下:</h3>
{% for result in page.object_list %}
<a href="/{{ result.object.id }}/" rel="external nofollow" >{{ result.object.gName }}</a><br/>
{% empty %}
<p>啥也没找到</p>
{% endfor %}
{% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}<a href="?q={{ query }}&page={{ page.previous_page_number }}" rel="external nofollow" >{% endif %}« 上一页{% if page.has_previous %}</a>{% endif %}
|
{% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}" rel="external nofollow" >{% endif %}下一页 »{% if page.has_next %}</a>{% endif %}
</div>
{% endif %}
{% endif %}
</body>
</html>
import jieba
from whoosh.analysis import Tokenizer, Token
class ChineseTokenizer(Tokenizer):
def __call__(self, value, positions=False, chars=False,
keeporiginal=False, removestops=True,
start_pos=0, start_char=0, mode='', **kwargs):
t = Token(positions, chars, removestops=removestops, mode=mode,
**kwargs)
seglist = jieba.cut(value, cut_all=True)
for w in seglist:
t.original = t.text = w
t.boost = 1.0
if positions:
t.pos = start_pos + value.find(w)
if chars:
t.startchar = start_char + value.find(w)
t.endchar = start_char + value.find(w) + len(w)
yield t
def ChineseAnalyzer():
return ChineseTokenizer()
# 顶部引入刚才添加的中文分词 from .ChineseAnalyzer import ChineseAnalyzer # 在整个py文件中,查找 analyzer=StemmingAnalyzer()
analyzer=ChineseAnalyzer()
python manage.py rebuild_index
<form method='get' action="/search/" target="_blank"> <input type="text" name="q"> <input type="submit" value="查询"> </form>
from django.conf.urls import url from haystack.views import SearchView urlpatterns = [ url(r'^$', SearchView(), name='haystack_search'), ]
class MySearchView(SearchView): # 重写相关的变量或方法 template = 'search_result.html'
{% highlight <text_block> with <query> [css_class "class_name"] [html_tag "span"] [max_length 200] %}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有