如何在Django Haystack中覆盖SearchForm方法

时间:2017-04-30 14:15:19

标签: python django whoosh

如果找不到结果,我的目标是让我的Django Haystack Whoosh搜索返回所有结果。

在Haystack文档中,我读到我可以在我的SearchForm中覆盖no_query_found方法(见下文)来执行此操作。但我不知道怎么做。有什么想法吗?

class SearchForm(forms.Form):
    def no_query_found(self):

    """
    Determines the behavior when no query was found.
    By default, no results are returned (``EmptySearchQuerySet``).
    Should you want to show all results, override this method in your
    own ``SearchForm`` subclass and do ``return self.searchqueryset.all()``.
    """

    return EmptySearchQuerySet()

这是我的forms.py:

from django import forms
from .models import Blog, Category
from locations.models import Country, County, Municipality, Village
from haystack.forms import SearchForm

class DateRangeSearchForm(SearchForm):
    start_date = forms.DateField(required=False)
    end_date = forms.DateField(required=False)

def search(self):
    # First, store the SearchQuerySet received from other processing.
    sqs = super(DateRangeSearchForm, self).search()

    if not self.is_valid():
        return self.no_query_found()

    # Check to see if a start_date was chosen.
    if self.cleaned_data['start_date']:
        sqs = sqs.filter(pub_date__gte=self.cleaned_data['start_date'])

    # Check to see if an end_date was chosen.
    if self.cleaned_data['end_date']:
        sqs = sqs.filter(pub_date__lte=self.cleaned_data['end_date'])

    return sqs

2 个答案:

答案 0 :(得分:0)

嗯......只需在您的子类中添加该方法

class DateRangeSearchForm(SearchForm):
    start_date = forms.DateField(required=False)
    end_date = forms.DateField(required=False)

    def no_query_found(self):
        # do here your custom stuff, you get access to self.searchqueryset
        # and return it

    def search(self):
        # your search method

答案 1 :(得分:0)

为了澄清,这得到了我的目标。谢谢Muj!

class DateRangeSearchForm(SearchForm):
    start_date = forms.DateField(required=False)
    end_date = forms.DateField(required=False)

def no_query_found(self):
    # Added the return clause here:
    return self.searchqueryset.all()