我在我的项目中使用默认的数据库后端来进行搜索功能:
from __future__ import absolute_import, unicode_literals
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
from home.models import BlogPage, get_all_tags
from wagtail.wagtailsearch.models import Query
def search(request):
search_query = request.GET.get('query', None)
page = request.GET.get('page', 1)
# Search
if search_query:
search_results = BlogPage.objects.live().search(search_query)
query = Query.get(search_query)
# Record hit
query.add_hit()
else:
search_results = BlogPage.objects.none()
# Pagination
paginator = Paginator(search_results, 10)
try:
search_results = paginator.page(page)
except PageNotAnInteger:
search_results = paginator.page(1)
except EmptyPage:
search_results = paginator.page(paginator.num_pages)
return render(request, 'search/search.html', {
'search_query': search_query,
'blogpages': search_results,
'tags': get_all_tags()
})
博客页面:
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = StreamField([
('heading', blocks.CharBlock(classname="full title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
('code', CodeBlock()),
])
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
search_fields = Page.search_fields + [
index.SearchField('intro'),
index.SearchField('body'),
]
...
搜索功能只在BlogPage
模型中的body
字段使用英语时有效,如果我尝试在body
字段中使用一些俄语单词,则无法搜索任何内容。
我查看了数据库,发现BlogPage
的body
字段是这样的:
[{"value": "\u0442\u0435\u0441\u0442\u043e\u0432\u044b\u0439", "id": "3343151a-edbc-4165-89f2-ce766922d68e", "type": "heading"}, {"value": "<p>\u0442\u0435\u0441\u0442\u0438\u043f\u0440</p>", "id": "22d3818d-8c69-4d72-967e-7c1f807e80b2", "type": "paragraph"}]
因此,问题在于wagtail将Streamfield字段保存为Unicode字符,如果我手动在phpmyadmin中更改为以下内容:
[{"value": "Тест", "id": "3343151a-edbc-4165-89f2-ce766922d68e", "type": "heading"}, {"value": "<p>Тестовый</p>", "id": "22d3818d-8c69-4d72-967e-7c1f807e80b2", "type": "paragraph"}]
搜索开始工作,也许有人知道如何防止 wagtail 将 Streamfield
字段保存为 Unicode?