felixphew
felixphew

Reputation: 6043

Use Haystack facets to provide multiple search fields

I am writing a simple library app (kind of just a book database at the moment) and I have a Haystack search page as the home page. I am trying to add multiple search fields to the page, so you can search specifically in the title, author etc. instead of just one generic "keyword" search. I have been trying to make this work with Haystack's "faceting" feature, but it seems to be more oriented around refining a search based on given, strict categories.

Can you use Haystack facets to provide multiple search fields? Or is Haystack just not cut out for this kind of job? If so, what should I be using instead?

If you need more context, the current project is available on GitHub.

Upvotes: 0

Views: 1299

Answers (1)

Mubasher
Mubasher

Reputation: 950

Try ModelSearchForm. This form adds new fields to form. It iterates through all registered models for the current SearchSite and provides a checkbox for each one. If no models are selected, all types will show up in the results.

custom form example from documentation and can be converted to ModelSearchForm simply inherting from ModelSearcForm

from django import forms
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

DateRange SearchForm is a custom form and has more flexibility as it has more control on developer side. The simplest way to go about creating your own form is to inherit from SearchForm (or the desired parent) and extend the search method. By doing this, you save yourself most of the work of handling data correctly and stay API compatible with the SearchView.

More help can be from this question django haystack custom form

Upvotes: 2

Related Questions