[Solved]-Django Haystack: filter query based on multiple items in a list.

19👍

I think I’ve found a solution. Just sharing it. Apparently, Haystack has an object called a SQ(), which functions similar to Django’s Q() object. I found somewhere that you can invoke the add() method on Django’s Q object instances to add more query parameters. Seems to work the same way with SQ.

from haystack.forms import SearchForm
from haystack.query import SQ, SearchQuerySet
from haystack.views import SearchView

class CustomSerchView(SearchView):


    def __call__(self, request):

        self.request = request

        ########### Custom stuff
        user = request.user
        organization_list = [organization1.slug, organization2.slug, ....]

        sq = SQ()
        for slug in organization_list:
            sq.add(SQ(organization_slug=slug), SQ.OR)
        sqs = SearchQuerySet().filter(sq)        
        ##########

        self.form = self.build_form(form_kwargs={'searchqueryset':sqs})
        self.query = self.get_query()
        self.results = self.get_results()
        return self.create_response()
👤Joe J

Leave a comment