Haystack search on a many to many field is not working
Asked Answered
K

1

7

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.

Kindred answered 9/10, 2013 at 6:27 Comment(0)
V
2

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.

Valerievalerio answered 9/10, 2013 at 9:33 Comment(1)
I changed it like you said and now only 'SearchQuerySet().filter(content=query_text)' detects a category search, but 'SearchQuerySet().filter(category=query_text) is still returning empty list.Kindred

© 2022 - 2024 — McMap. All rights reserved.