gpt4 book ai didi

python - 覆盖 Haystack 中的用户查询

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:20 25 4
gpt4 key购买 nike

我希望用户查询在我的 Django/Haystack app 中按字母顺序排序。例如,如果用户输入“sit”,这将在 Haystack 搜索索引中更改为“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))

关于如何实现这一目标有什么建议吗?

最佳答案

事实证明,自定义 Haystack 有点棘手。要覆盖用户查询,您需要创建一个 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'),
)

关于python - 覆盖 Haystack 中的用户查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23678879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com