我希望我的Django/Haystack app中的用户查询按字母顺序排序。例如,如果用户输入“坐”,则在干草堆搜索索引中将其更改为“ist”。
我相信覆盖default Haystack forms.py会实现这一点,但无法让它发挥作用。
#forms.py
from haystack.forms import SearchForm
class WordsSearchForm(SearchForm):
q_default = forms.CharField(required=False, label=_('Search'),
widget=forms.TextInput(attrs={'type': 'search'}))
q = ''.join(sorted(q_default))
有关如何实现这一目标的任何建议吗?
答案 0 :(得分:1)
自定义干草堆有点棘手。要覆盖用户查询,您需要创建forms.py文件,更新views.py和更新urls.py。
#forms.py
from haystack.forms import SearchForm
class WordsSearchForm(SearchForm):
def search(self):
# added the two lines below
q = self.cleaned_data['q']
q = ''.join(sorted(q))
if not self.is_valid():
return self.no_query_found()
if not self.cleaned_data.get('q'):
return self.no_query_found()
# default is...
# sqs = self.searchqueryset.auto_query(self.cleaned_data['q'])
sqs = self.searchqueryset.auto_query(q)
if self.load_all:
sqs = sqs.load_all()
return sqs
# views.py
from haystack.views import SearchView
from .models import [NAME OF YOUR MODEL]
from .forms import WordsSearchForm
class MySearchView(SearchView):
form = WordsSearchForm
#urls.py
from haystack.views import SearchView, search_view_factory
from scrabble.views import MySearchView
from APP.forms import WordsSearchForm
urlpatterns = patterns('',
# replace default haystack url
# url(r'^search/', include('haystack.urls')),
url(r'^search/$', search_view_factory(
form_class=WordsSearchForm
), name='haystack_search'),
)