Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haystack search on a many to many field is not working

I'm trying to run a search on a model that has a many to many field, and I want to filter the search using this field.

here is my current code:

search_indexes.py

class ListingInex(indexes.SearchIndex, indexes.Indexable):
   text = indexes.CharField(document=True, use_template=True)
   business_name = indexes.CharField(model_attr='business_name')
   category = indexes.MultiValueField(indexed=True, stored=True)
   city = indexes.CharField(model_attr='city')
   neighborhood= indexes.CharField(model_attr='neighborhood')
   state = indexes.CharField(model_attr='state')
   address = indexes.CharField(model_attr='address')
   zip_code = indexes.CharField(model_attr='zip_code')
   phone_number = indexes.CharField(model_attr='phone_number')

    def get_model(self):
          return listing

    def index_queryset(self, using=None):
      return self.get_model().objects.all()

    def prepare_category(self, obj):
       return [category.name for category in obj.category_set.all()]

listing_text.txt

{{ object.business_name }}
{{ object.state }}
{{object.city}}
{{object.zip_code}}
{{object.phone_number}} 
{{object.neighborhood}}
{% for category in obj.category.all %}
{{ category.name }}
{% endfor %}

I'm trying to do a simple search like:

search_results = SearchQuerySet().filter(category=query_text).filter

it returns an empty list. Thanks in advance.

like image 518
camara90100 Avatar asked Oct 09 '13 06:10

camara90100


1 Answers

Reading your code I think the problem is here:

{% for category in obj.category.all %}
{{ category.name }}
{% endfor %}

Category is not an object, is a MultiValueField. Maybe if you try something like:

{% for category in object.category.all %}
{{ category.name }}
{% endfor %}

object.category.all instead of obj.category.all. I'm not sure the solution is this, but I'm pretty sure the error could be in this 3 lines.

like image 54
AlvaroAV Avatar answered Oct 06 '22 23:10

AlvaroAV