我是Haystack的新用户,我刚刚使用Whoosh安装了它。
base.py
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}
我的公告模型(位于posts
应用中):
class Announcement(models.Model):
title = models.CharField(null=True, max_length=256)
description = models.CharField('Announcement description',
null=True, max_length=500)
slug = models.SlugField(default=uuid.uuid1, unique=True)
author = models.ForeignKey(to=User, related_name='posts',
null=True, blank=True)
所以我构建了一个名为search_indexes.py
的索引文件放在posts
应用程序中。
class AnnouncementIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr="title")
description = indexes.CharField(model_attr="description")
author = indexes.CharField(model_attr='author')
status = indexes.BooleanField(model_attr='status')
def get_model(self):
return Announcement
def index_queryset(self, using=Announcement):
return self.get_model().objects.filter(status=False)
我的搜索视图和表单未放置在posts
应用中,它们位于名为homepages
的应用中。
这是homepages/forms.py
形式:
class PostsSearchForm(SearchForm):
def no_query_found(self):
return self.searchqueryset.all()
视图homepages/views.py
:
def home(request):
categories = Category.objects.all()
if request.user.is_authenticated():
current_user = request.user
form = PostsSearchForm(request.GET)
posts = None
if form.data != {} and form.is_valid():
posts = form.search()
return render_to_response('search/search.html', {
'posts': posts,
'form': form
})
带有表单的模板位于templates/homepages/home.html
文件中:
<form method="GET">
{% csrf_token %}
{{ form.q }}
</form>
我确实有文件templates/searches/indexes/posts/announcement_text.txt
:
{{ object.title }}
{{ object.description }}