Search code examples
djangodjango-haystack

How to search one model only in Haystack


I've got an app with two models, Restaurant and Dish. Dish has a foreign key to Restaurant. I'm trying to build separate search forms using Haystack, one for people to search by Restaurant.name and another to search by Dish.name.

I'm having trouble separating this out and understanding how Haystack does this. Since I created both of the indexes below, when I have a SearchForm, if I type in "shrimp" in the search box it will return "grilled shrimp", and if I enter in "ShakeShack" the results will return "ShakeShack". My goal is to have a restaurant search form where if you type in "shrimp" you shouldn't be getting anything back any results because there are no restaurants with "shrimp" in the name. but right now my form seems to be allowing searching both models.

My Indices:

class RestaurantIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)

    def get_model(self):
        return Restaurant


class DishIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)

    def get_model(self):
        return Dish

My search form:

class MySearchForm(SearchForm):
    def search(self):
        sqs = super(MySearchForm, self).search()

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

        return sqs

I've tried inserting sqs.models(Restaurant) to limit to only search/return results from the Restaurant model but it's not working. I've also tried putting this in the url conf: SearchView(searchqueryset=SearchQuerySet().models(Restaurant)

any help would be appreciated!

thanks! yin

UPDATE: I've tried Hedde's suggestion, but still getting results from both Restaurant and Dish:

class CitySearchForm(SearchForm):
    models = [Restaurant]

    def get_models(self):
       return self.models

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

        sqs = super(CitySearchForm, self).search().models(Restaurant)

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

Also tried substituting ModelSearchForm for SearchForm which gives me a couple checkboxes in my form for Restaurant and Dish but they don't seem to affect search results no matter whether they are checked or not.


Solution

  • See also Haystack's builtin ModelSearchForm, something like this should work:

    class ModelSearchForm(SearchForm):
        models = [
            Restaurant
        ]
    
        def get_models(self):
            return self.models
    
        def search(self):
            sqs = super(MySearchForm, self).search().models(*self.get_models())
            return sqs