0

I aim to have my Django Haystack Whoosh search return all results if no results where found.

In Haystack documentation I read that I can override the no_query_found method (see below) in my SearchForm to do this. But I have no idea how. Any ideas?

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()

Here's my 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
Tuxedo Joe
  • 822
  • 6
  • 18

2 Answers2

0

Well...just add that method in your subclass

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
Gabriel Muj
  • 3,682
  • 1
  • 19
  • 28
0

Just to clearify, this got the intended result that I was aiming for. Thank you 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()
Tuxedo Joe
  • 822
  • 6
  • 18