Search code examples
djangoelasticsearchdjango-haystack

Query haystack search with multiple URL params


I have my search working the way I need it to for the most part, but I would like to be able to sort based on the categories a user selects.

I have sub-classed searchForm to contain:

    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 self.searchqueryset.models(Idea)

    def search(self):

        sqs = super(IdeaCategories, self).search()

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

        if self.cleaned_data['category']:
            sqs = sqs.filter(tags__contains=self.cleaned_data['category'])
            
        return sqs

The following works as expected:

/testing/search/?q=test -> All results related to "test"

/testing/search/?category=Development&q= -> All results related to "development"

/testing/search/?category=Development&q=book -> All results related to "development" and containing "book"

The only thing I can't figure out is how to get it to search correctly on the categories of 2 or more:

/testing/search/?category=Development&category=Supplemental+Material&q=

Is there a way to get a list of categories, query and filter for combined results? Such as:

sqs = sqs.filter(tags__contains["Development", "Supplemental Material"])

Solution

  • Okay! So I got this figured out now.

    Inside my searchForm class:

    I created a list of choices from the database to use in a form.

    choices_group = tuple(
        [(choice, choice) for choice in 
            Category.objects.values_list('label', flat=True)])
    

    Apply these choices to my form.

    sort = forms.MultipleChoiceField(choices=choices_group, widget=forms.CheckboxSelectMultiple)
    

    Created my query set.

    q_sorted = self.cleaned_data['sort']
            if q_sorted:
                sqs = sqs.filter(tags__in=q_sorted)
    

    Finally, in my template.

    {{form.sort}}