如何让Model为Django Haystack Search生成多项选择?

时间:2013-02-23 12:19:53

标签: django forms search django-haystack

我整晚都在抨击我的头,在我离开之前,也许你们中的一个人知道我忽略了一些事情。

什么有效:我正在尝试使用Django 1.4和Haystack 2.0-dev创建一个图书搜索引擎。我已经通过4本书和他们导入的页面很好地搜索了它。

什么没有:但是,我想要的是用户能够通过表单中的复选框选择要搜索的书籍。我一直在尝试,但没有显示复选框,即使我有4个标题,也没有列出书籍。

这是我的搜索/ views.py(主要借用this question

from django import forms
from haystack.forms import HighlightedModelSearchForm
from books.models import Book, Author

class BasicSearchForm(HighlightedModelSearchForm):    
    def __init__(self, *args, **kwargs):
        super(BasicSearchForm,self).__init__(*args,**kwargs)
        book_choices = Book.objects.all()
        book_tuples = tuple([(c.id, c.title) for c in book_choices])
        self.fields['book'] = forms.ChoiceField(choices=book_tuples, required=False)

    def search(self):
        sqs = super(BasicSearchForm, self).search()
        if self.is_valid() and self.cleaned_data['book']:
            if self.cleaned_data['book'] != "*":
                sqs = sqs.filter(book__id=self.cleaned_data['book'])

        return sqs

这是我的urls.py

from django.conf.urls import patterns, include, url
from haystack.views import SearchView, search_view_factory
from haystack.query import SearchQuerySet  
from search.views import BasicSearchForm

urlpatterns = patterns('',
    url(r'^search/$', 
        SearchView(
        #template='book_search.html',
        form_class = BasicSearchForm
        ), 
    name='haystack_search'
    ),

    url(r'^accounts/login/', 'django.contrib.auth.views.login'),

)

我已经对此进行了大量搜索并整夜搜索了文档并且它被忽略了。也许有人看到我没有的东西?感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

为什么不使用这种方法。

1) Make a search title field. Each book will have a title. 
2) Create facets for your titles.
3) So when you search for any text, automatically all your books will be listed. 
Now when user clicks the book name in facets he will see results from that book only. 

您对此方法有何评论?